조회수 기능을 구현할 때 한 번 조회를 한 유저는 일정 시간 동안 다시 조회수를 증가시키지 못하게 만들고 싶었다.
redis를 사용했다.
1. 설치
ubuntu에 명령어
sudo apt-get update
sudo apt-get install redis-server
redis-cli ping (이 명령어 후 "PONG"을 반환받으면 redis가 정상적으로 동작 중임)
npm 명령어
npm install ioredis
2. 설정
sudo nano /etc/redis/redis.conf
nano는 vim처럼 리눅스에서 파일을 수정할 수 있게 해주는 프로그램이다.
redis.conf에서
bind 0.0.0.0 (<-요청을 허용하는 주소)
requirepass RedisPassword (<-비밀번호)
3. 기본 메소드
redis.set(key, value);
redis.get(key); (Promise 반환)
redis.ttl(key);
redis.expire(key, cooldownTime);
4. 내 코드
const Redis = require('ioredis');
const redis = new Redis({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
});
const increaseViewCount = async (clientIp, video) => {
const key = clent-ip:${clientIp}:video:${video.id}:views;
// Redis에서 TTL 확인
const ttl = await redis.ttl(key);
if (ttl > 0) {
console.log(조회수 증가가 ${ttl}초 동안 막혔습니다.);
return false; // 조회수 증가 막힘
} else {
const cooldownTime = 15 * 60; // 15분
video.views++; // 조회수 1 증가
await video.save();
await redis.set(key, 1);
// TTL 설정 (15분 동안)
await redis.expire(key, cooldownTime);
console.log(`조회수 증가: ${video.views}`);
return true; // 조회수 증가 성공
}
}
const clientIp = req.ip;
await increaseViewCount(clientIp, video);