2017년 8월 12일 토요일

Spring redis client 설정

cache memory중 하나인 redis를 사용하기 위해서, 여러가지 client를 사용할 수 있지만
여기서는 spring과 연동하기 쉬운 lettuce를 사용하여 redis에 접속해보도록 하자.

가장 먼저, 아래와 같이 lettuce를 dependency에 추가하도록 하자.

compile group: 'biz.paluch.redis', name: 'lettuce', version: '4.4.0.Final'

그리고 나서, 아래와 같이 bean으로 redis client를 설정해주면 끝~!!

@Configuration
public class LettuceConfig {

    @Bean(destroyMethod = "shutdown")
    ClientResources clientResources() {
        return DefaultClientResources.create();
    }

    @Bean(destroyMethod = "shutdown")
    RedisClient redisClient(ClientResources clientResources) {
        return RedisClient.create(clientResources, RedisURI.create("192.168.1.63", 6379));
    }

    @Bean(destroyMethod = "close")
    StatefulRedisConnection connection(RedisClient redisClient) {
        return redisClient.connect();
    }

}

redisClient를 사용하여, string을 set한 후, get을 하면 아래와 같은 결과를 볼 수 있다.

2017-08-12 20:59:37.054  INFO 7564 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-12 20:59:37.091  INFO 7564 --- [           main] org.blog.test.LettuceApplication         : result : Hello, Redis!
2017-08-12 20:59:39.310  INFO 7564 --- [           main] org.blog.test.LettuceApplication         : Started LettuceApplication in 6.503 seconds (JVM running for 7.218)

전체 예제는 아래 링크에서 다운로드 가능하다.

https://gitlab.com/shashaka/lettuce-redis-project

댓글 없음 :

댓글 쓰기