코딩과 결혼합니다

[Game-Crew] 트러블 슈팅 : 유저 평점 조회 API 캐싱 (실패) 본문

코딩과 매일매일♥/Game_Crew

[Game-Crew] 트러블 슈팅 : 유저 평점 조회 API 캐싱 (실패)

코딩러버 2024. 1. 16. 16:56
728x90
    private final RedisTemplate<String, UserRatingsResponseDto> redisTemplate;

@GetMapping("/rating/{evaluated_user}")
    public UserRatingsResponseDto getUserRatings(
            @PathVariable Long evaluated_user,
            @RequestParam int page,
            @RequestParam int size
            ){
        String cacheKey = "evaluatedUser:" + evaluated_user + ":page:" + page + ":size:" + size;

        // 캐시에서 평가 정보 조회
        UserRatingsResponseDto cachedResponse = redisTemplate.opsForValue().get(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }

        // 캐시에 없는 경우 기존 로직으로 평가 정보 조회
        UserRatingsResponseDto response = ratingService.getUserRatings(evaluated_user, page - 1, size);

        // 조회한 평가 정보를 캐시에 저장
        redisTemplate.opsForValue().set(cacheKey, response);

        return response;
    }

 

Controller 단에 캐싱하고 싶은 부분에 대하여 캐시에 이미 존재하면 그대로 반환, 없으면 기존의 로직을 처리한 뒤에 

캐싱하도록 하였다.

 

Troubleshooting(1)

▪️ RedisTemplate의 빈을 찾을 수 없다.

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-01-16T16:39:59.955+09:00 ERROR 34224 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 2 of constructor in com.gamecrew.gamecrew_project.domain.user.controller.RatingController required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.

 

✔️ port번호와 host 설정을 해주었다. 

#redis
spring.data.redis.host=localhost
spring.data.redis.port=6379

 

이것도 마찬가지로 설정을 해주어야 사용할 수 있다고 한다.

 

✔️Config

@Configuration
public class RedisConfig {
    @Value("${spring.data.redis.host}")
    private String host;

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

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new LettuceConnectionFactory(host, port);
    }
    @Bean
    public RedisTemplate<String, UserRatingsResponseDto> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, UserRatingsResponseDto> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(new GenericToStringSerializer<>(UserRatingsResponseDto.class));
        return template;
    }
}

 

 

Redis와의 상호작용을 담당하는 클래스로 이를 사용하여 캐시 데이터를 읽고 쓸 수 있다.

어플리케이션의 실행이 잘 됨을 확인하였다.

 

 

Troubleshooting(2)

▪️ 접속 거부 오류 - 서버와의 연결에 문제가 있는 경우 발생

2024-01-16T19:21:42.942+09:00 ERROR 2432 --- [0.0-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis] with root cause

java.net.ConnectException: Connection refused: no further information
	at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
	at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
	at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:946) ~[na:na]
	at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:337) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:776) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) ~[netty-transport-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.97.Final.jar:4.1.97.Final]
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.97.Final.jar:4.1.97.Final]
	at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

 

  1. Redis 서버가 실행 중이지 않거나, 잘못된 호스트 및 포트를 사용하고 있는 경우 
  2. spring.data.redis.host'와 'spring.data.redis.port' 프로퍼티가 올바른 Redis 서버의 호스트와 포트를 가리키고 있는지
  3. 네트 워크 연결 상태  (Redis 서버에 접속할 수 있는지? 방화벽등이 Redis 접속을 차단하고 있는지)

🤔  임베디드 레디스의 경우에 따로 서버를 실행시켜 주지 않아도 실행이 가능하다고 알고 있다.
🤔  호스트 및 포트를 알맞게 사용하는듯 보이지만 더 알아봐야겠다.

계속 해결되지 않는다면 임베디드 레디스를 쓰지 않고 맘 편하게 redis 설치후에 여러 레퍼런스를 참고하여 다시 시도해봐야겠다...