본문 바로가기
web/SpringBoot

SpringBoot 에 Redis 연동하기

by 뽀리님 2023. 11. 27.

설치는 아랫글 참조

https://ssmyefrin.tistory.com/47

 

Redis 설치하기(cli로 설치)

실행환경 MAC(intel) 기준 1 설치하기 $brew install redis 2 실행하기 $brew services start redis $brew services stop redis $brew services restart redis $redis-server 3 설정파일경로 $ /usr/local/etc/redis.conf 4.실행하기 Medis 를 설

ssmyefrin.tistory.com

 

 

간단하게 SpringBoot 와 연동해보려고 한다.

 

 실행환경

-IntelliJ + SpringBoot 3.1.5 + JDK17
-MAC OS(intel)
-Redis (Medis)

 

 

간단히 조회성만 할것이기에 StandardAlone 으로 구성하였다.

필요하다면 Cluster 구성을 해야한다.(주로 클러스터로 구성하는편이다. 하지만 나는 테스트기에..) 

 

1. 의존성추가 : Lettuce Redis Cluster 적용

// Redis lettuce
implementation group: 'io.lettuce', name: 'lettuce-core', version: '6.1.8.RELEASE'

redis의 클러스터를 이용해 데이터들을 샤딩 할수 있다. 스프링 부트에서 기본 레디스 라이브러리는 lettuce 이다.

 

 

2. 설정 Config 추가

@Slf4j
public class KakaoRedis implements AutoCloseable {
    private RedisURI redisURI;
    private RedisClient redisClient;
    private RedisClusterClient redisCluster;
    private StatefulRedisConnection<String, String> connection;
    private StatefulRedisClusterConnection<String, String> connection_;

    public KakaoRedis(String redisUrl){
        this.redisURI =  RedisURI.Builder.redis(redisUrl).build();
    }
    public KakaoRedis(String redisUrl, int port){
        this.redisURI = RedisURI.Builder.redis(redisUrl, port).build();
    }

    /**
     * 클러스터용
     * @return
     */
    public RedisAdvancedClusterCommands<String, String> getClusterRedisCommands(){
        this.redisCluster = RedisClusterClient.create(Arrays.asList(this.redisURI)); // 인스턴스생성
        this.connection_ = redisCluster.connect(); // 접속
        // failover set
        ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                .enablePeriodicRefresh(Duration.ofSeconds(60))
                .enableAllAdaptiveRefreshTriggers()
                .build();

        redisCluster.setOptions(ClusterClientOptions.builder()
                .topologyRefreshOptions(topologyRefreshOptions)
                //.autoReconnect(false)
                .build());

        RedisAdvancedClusterCommands<String, String> syncCommands = connection_.sync(); // 명령 인스턴스
        return syncCommands;
    }

    /**
     * 싱글노드용
     * @return
     */
    public RedisCommands<String, String> getRedisCommands(){
        this.redisClient = RedisClient.create(this.redisURI);
        this.connection = redisClient.connect();
        RedisCommands<String, String> syncCommands = connection.sync();
        return syncCommands;
    }


    @Override
    public void close() throws Exception {
        if (connection != null && connection.isOpen()) {
            connection.close();
            redisClient.shutdown();
        }
        if (connection_ != null && connection_.isOpen()) {
            connection_.close();
            redisCluster.shutdown();
        }
    }

}

 

나는 클러스터와 싱글노드 모두 구현하였다.

자동으로 클로징해주기위헤 AutoClose 를 임플리먼트하고 오버라이드로 정의해줬다.

 

3. 서비스등록

@Service
@RequiredArgsConstructor
@Slf4j
public class RedisService {
    @Value("${address.redis}")
    private String redisUrl;

    @Value("${address.port}")
    private int redisPort;

    /**
     * 코드등록
     * @param code
     * @param value
     */
    public void redisRegistCode(String code, String value){
        try (KakaoRedis kakaoRedisConfig = new KakaoRedis(redisUrl,redisPort)) {
            RedisCommands<String, String> syncCommands = kakaoRedisConfig.getRedisCommands();
            syncCommands.set(code, value);
        } catch (Exception e){
            log.error("[Redis Regist EXCEPTION]:"+e.getMessage(),e);
        }
    }

    /**
     * 코드조회
     * @param code
     * @return
     */
    public String redisGetCode(String code){

        String value = "";
        try (KakaoRedis kakaoRedisConfig = new KakaoRedis(redisUrl,redisPort)) {
            value = kakaoRedisConfig.getRedisCommands().get(code);
        } catch (Exception e){
            log.error("[Redis Regist EXCEPTION]:"+e.getMessage(),e);
        }
        return value;
    }
}

 

간단하게 컨트롤러에서 코드값과 밸류값을 받은 후  조회하는 코드이다.

 

 

4. 컨트롤러등록

@RequestMapping("common")
public class TodoController {
    private final RedisService redisService;

    @GetMapping("/hello")
    public String hello() {
        return "Hello backend service";
    }

    @PostMapping("/code/regist")
    public ResponseEntity<?> codeRegist(@RequestParam String code, @RequestParam String value) {
        redisService.redisRegistCode(code,value);
        return ResponseEntity.ok().body("success");
    }

    @GetMapping("/code/search")
    public ResponseEntity<?> codeRegist(@RequestParam String code) {
        String val = redisService.redisGetCode(code);
        return ResponseEntity.ok().body(val);
    }


}

 

 

 

5. 테스트

코드 등록

 

 

Redis 에 잘 등록되었다.

 

 

 

코드조회