Redis Cache
2024. 10. 11. 11:41ㆍSpring Boot
Spring Boot에서 Redis를 이용해서 캐싱을 하는 방법을 알아보겠다
우선 기본적으로 redis를 연결해주고
캐시에 필요한 라이브러리를 추가해준다.
implementation 'org.springframework.boot:spring-boot-starter-cache'
package com.example.mvc.redis;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@EnableCaching
@Configuration
public class CacheConfig {
@Bean
public CacheManager contentCacheManager(RedisConnectionFactory cf) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer)) // Value Serializer 변경
.entryTtl(Duration.ofMinutes(3L)); // 캐시 수명
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(cf).cacheDefaults(redisCacheConfiguration).build();
}
}
그 후 CacheManager을 필요에 따라 세팅해준다
보통 저장하는 데이터가 객체이기 때문에 직렬화가 필요한데
이번에는 보편적으로 많이 쓰이는 Serializer를 사용하고
거기에 LocalDateTime을 직렬화 할 수 있도록 수정을 했다.
이렇게 CacheManager를 세팅한 뒤에
기본적으로
@Cacheable
@CacheEvict
@CachePut
세가지를 이용해 캐쉬 전략을 짜준다
우선 @Cacheable은 주로 읽기에 쓰이는 어노테이션이다
해당 어노테이션을 이용하면 캐쉬에 값이 있는지 확인하고 없으면 값을 읽어오고 캐쉬에 값을 넣는다
주로 쓰기에 쓰이는 어노테이션이다
@CacheEvict은 해당 하는 데이터를 캐쉬에서 삭제하는 역할을 한다
이를 통해 db등의 값이 바뀌었을때 캐쉬를 비워서 바뀐 값을 불러 올때는 db와 통신을 하게 해서 캐쉬와 db간의 일관성을 유지한다.
@CachePut은 작업의 결과를 캐쉬에 저장한다
이를 통해 값을 바꾸는 작업을 시행할 때 캐쉬와 db간의 일관성을 유지한다.
@Cacheable(value = "board", key = "#id", cacheManager = "contentCacheManager")
public postgre_data get_data(Long id) {
Optional<postgre_data> tmp = repo.findById(id);
if(tmp.get() == null) {
return null;
}
return tmp.get();
}
@Transactional
@CacheEvict(value = "board", key="#id", cacheManager = "contentCacheManager")
public postgre_data update_data(Long id, String title, String data) {
postgre_data update = repo.findById(id).get();
update.setData(data);
update.setTitle(title);
update.setCreatedAt(LocalDateTime.now());
return update;
}
캐시 적용 전


캐시 적용 후


'Spring Boot' 카테고리의 다른 글
| Spring Cloud Gateway Filter (0) | 2024.10.29 |
|---|---|
| Spring Cloud Gateway (2) | 2024.10.25 |
| WebMVC와 WebFlux를 동시 사용 할 경우 WebSocket (0) | 2024.08.14 |
| OSIV (0) | 2024.08.03 |
| @Transactional 과 영속성 (0) | 2024.08.02 |