티스토리 뷰

여기서는 Jedis가 아닌 Lettuce를 이용하여 연계를 했다.

Lettuce는 Netty 기반의 Redis Client로 비동기로 요청을 처리하여 성능에 장점이 있어 사용했다.

일단 Jedis 기반처럼 Pool을 별도로 사용하지 않아도 돼서 개발에 편한점도 한몫함.

 

 

Dependency 추가

아래 dependency만 추가해주면 사용 가능하다.

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 

Redis 설정 추가

 

Redis의 host와 port 정보를 application.yml 파일에 설정

spring:
    redis:
        lettuce:
            pool:
                max-active: 10
                max-idle: 10
                min-idle: 2
        port: 6379
        host: 127.0.0.1
        channel: foo

 

아래 Redis 관련 Configuration 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Configuration
public class RedisConfig {
 
    @Value("${spring.redis.host}")
    private String redisHost;
 
    @Value("${spring.redis.port}")
    private int redisPort;
 
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(redisHost);
        redisStandaloneConfiguration.setPort(redisPort);
        // 패스워드 있으면 설정
//        redisStandaloneConfiguration.setPassword(redisPwd);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration);
        return lettuceConnectionFactory;
    }
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

}

 

 

중간에 RedisTemplate Bean 등록 시 [26 Line] 에서 GenericJackson2JsonRedisSerializer() 로 셋팅하는 부분은 데이터 형태를 하나의 표준화 된 VO형태가 아니라 여러가지 형태로 공존할 수 있어서 이렇게 셋팅함.

그럼 아래와 같은 @class 데이터가 붙어서 Serializer를 통해 객체로 변경해줄 때 어떤 VO로 매핑할 지 체크한다.

{"@class":"com.example.demo.common.redis.RedisVO","key1":"value1","key2":"value2"}


※ 표준화 된 하나의 VO만 사용하면 해당 코드를 아래와 같이 변경

   redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(RedisVO.class)); 

 

 

Redis Set/Get 사용

간단히 사용방법만 소개하기 위해서 Test 코드로 작성했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
 
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
 
    @Test
    public void redisBasicFunction_guide() throws JSONException {
        //Given
        String key = "iamkey";
        String value = "iamvalue";
        
        // redis에 set
        redisTemplate.opsForValue().set(key, value);
        
        // redis에서 get
        RedisVO redisVO = (RedisVO) redisTemplate.opsForValue().get(key);
        
        // redis에서 data delete
        
        // redis에 해당 key를 가지고 있는지 확인
        if (!redisTemplate.hasKey("999")) {
            System.out.println("key 미존재");
        }
    }
}
 
 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함