-
Spring cache abstraction 에 대한 간단한 예제spring 2023. 2. 26. 15:42
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#io.caching
Spring Boot Reference Documentation
This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly spe
docs.spring.io
spring-boot-starter-cache 로 cache abstraction 을 사용할 수 있다.
Cache provider bean 이 필요한데, CacheManager type 을 등록하면 된다.
등록하지 않을 경우 concurrent map (in-memory) 에 저장한다.
(최소한의 예제이다. 실제로 쓸 땐 더 커스터마이징 해서 쓸 수 있다..)
@Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(host, port); } @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues() .disableKeyPrefix() .entryTtl(Duration.ofSeconds(100)); RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder .fromConnectionFactory(redisConnectionFactory) .cacheDefaults(redisCacheConfiguration) .build(); return cacheManager; } @Cacheable("sample", key = "'cache:name:' + #name") public SampleData call(String name) { SampleData data = new SampleData(); data.setName(name); System.out.println("Save " + name); return data; } @Data public class SampleData implements Serializable { private String name; }Redis 에 SampleData 객체를 저장하는 캐싱 방식이고, cache:name:${name} 형식으로 저장되며 모든 캐시에 대해 TTL 은 100초이다.
@Cacheable 은 cacheNames, key 등 여러 파라미터가 있는데 key 는 SpEL 문법으로 적는다.
+ TTL 설정이 생각보다 까다롭다. 뭔가 좋은 방법이 있을거 같은데...
'spring' 카테고리의 다른 글
spring cloud gateway 에 대해 (0) 2023.03.12 Spring swagger 3.x openapi Authorization header 설정하기 예제 코드 (0) 2023.02.26 어떤 controller 에서 handler 하는지 못찾을 때 (0) 2023.02.13 Spring 어플리케이션을 설정하는 방법 (0) 2023.01.28 Spring boot vs spring + tomcat (0) 2023.01.01