반응형

블로그의 조회수를 저장하고 가져올 수 있도록 해야 할 거 같아서 해당 기능을 Redis로 사용해보려 했다.

 

당연히 redis를 build.gradle에 추가하고

implementation 'org.springframework.boot:spring-boot-starter-data-redis'

 

RedisConfig를 작성해줬다.

package cobo.blog.global.Config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableRedisRepositories
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new LettuceConnectionFactory(host, port);
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }
}

여기까지야 뭐... 그냥 다른 블로그들 찾아가며 작성했다.

 

당연히 괜찮을 줄 알았다....

 

이렇게 template을 작성하고

    public void RedisTest(){
        ValueOperations<String, Integer> stringIntegerValueOperations = redisTemplate.opsForValue();

        if(stringIntegerValueOperations.get("count") == null)
            stringIntegerValueOperations.set("count", 1);

        Long incrementedValue = stringIntegerValueOperations.increment("count");
        log.info("after increment: " + incrementedValue);
    }

이 코드를 실행해보았다.

 

하지만 이런 에러가 발생

난 분명히 1을 넣었는데, 증가할 수 없는 값이라고 한다.

 

redis로 바로 가서 확인해보았다.

내가 넣은 값이 이렇게 변환되어 저장이 되었고, 그렇기에 증가할 수 없었던 것이다.

 

이 부분을 바꾸고 싶다면 RedisTemplate을 다시 작성해야 한다.

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }

저장 하는 중에 Serialize하는 방법을 바꾸어 주면 해결이 된다.

 

    public void RedisTest(){
        ValueOperations<String, String> stringIntegerValueOperations = redisTemplate.opsForValue();

        if(stringIntegerValueOperations.get("count") == null)
            stringIntegerValueOperations.set("count", "1");

        Long incrementedValue = stringIntegerValueOperations.increment("count");
        log.info("after increment: " + incrementedValue);
    }

이렇게 코드르 수정하고 실행해보면 

잘 작동하는 것을 볼 수 있다.

'블로그 개발 프로젝트' 카테고리의 다른 글

조회수 중복 유저 제거  (0) 2023.08.10
Redis를 사용한 조회수 구현  (0) 2023.08.10
Nginx에 페이지 연결하기  (0) 2023.08.07
EC2에 Nginx 초기 설정  (0) 2023.08.05
ExceptionHandler  (0) 2023.07.28

+ Recent posts