Spring

Spring Data Redis

Mecodata 2024. 4. 18. 10:24

정의

- Spring Boot와 Redis 간의 상호작용이 가능하도록 제공하는 Spring Boot 외부 라이브러리

- Redis를 DB 또는 캐시로 사용하는 경우에 사용 (세션 관리일 경우에는 Spring Session Data Redis 사용)

- RedisTemplate 클래스를 사용하여 Redis와의 상호작용을 지원

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

 

RedisTemplate

정의 및 특징

- Redis에 데이터를 저장, 검색, 갱신 및 삭제하는 데 사용 (CRUD)

- 직렬화/역직렬화, 트랜잭션 처리, 파이프라인 지원 등을 포함한 다양한 기능을 제공

- Redis 트랜잭션 지원

- Redis 파이프라인 지원

- 제네릭(<>)을 이용하여 RedisTemplate의 키와 값의 타입을 정해줘야 함

주요 메소드

- expire(key, num, TimeUnit.단위) = 데이터의 유효 기간 설정

 

- opsForValue() = ValueOperations 객체 생성 (Redis에서의 자료구조 = String)

- opsForList() = ListOperations 객체 생성 (Redis에서의 자료구조 = List)

- opsForSet() = SetOperations 객체 생성 (Redis에서의 자료구조 = Set)

- opsForZSet() = ZSetOperations 객체 생성 (Redis에서의 자료구조 = Sorted Set)

- opsForHash() = HashOperations 객체 생성 (Redis에서의 자료구조 = Hash)

오퍼레이션(Operation) = Redis의 데이터 타입에 따른 작업 수행 메서드를 제공하는 인터페이스

- 오퍼레이션의 주요 메소드 = get(key), set(key, value), set(key, value, num, TimeUnit), append(key, value), size(key)

 

기본 세팅

RedisConfig

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String redisHost;
	
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean // Redis Connector로 Lettuce 사용 
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(redisHost, redisPort);
    }
    
    @Bean // 데이터 타입 <String, String> 사용
    public RedisTemplate<String, String> redisTemplate() {
    	StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory()); // Lettuce 적용
        return redisTemplate;
    }
	
}

- Redis Connector에는 Lettuce(비동기), Jedis(동기)가 있는데 더 나은 성능을 가진 Lettuce를 주로 사용

- StringRedisTemplate = RedisTemplate<String, String>

RedisTemplate 활용 예시

public class RedisTest {
	
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    public void redisSet(String key, String value) {
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        valueOps.set(key, value, 20, TimeUnit.MINUTES); // 유효 기간 20분으로 데이터를 Redis에 저장
    }

    public String redisGet(String key) {
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
    	String value = valueOps.get(key);
        return value;
    }
    
}