728x90
Spring Boot에 Cache넣기
spring-boot-starter-cache만 import 하면 ConcurrentHashMap이 캐쉬 클래스가 된다.
이 클래스는 expire를 수동으로 해줘야 한다.
그래서 expire time을 줄 수 있는 caffein cache를 쓰는 것.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.6.2</version>
</dependency>
main(){
@SpringBootApplication
@EnableCaching
public class ChartDataServer extends SpringBootServletInitializer {}
CacheType.java
@Getter
public enum CacheType {
ARTISTS("subsidy_info", 10, 100),
ARTIST_INFO("subsidy_accepted", 10, 100);
CacheType(String cacheName, int expiredAfterWrite, int maximumSize) {
this.cacheName = cacheName;
this.expiredAfterWrite = expiredAfterWrite;
this.maximumSize = maximumSize;
}
private String cacheName;
private int expiredAfterWrite;
private int maximumSize;
}
CacheConfig.java
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<CaffeineCache> caches = Arrays.stream(CacheType.values())
.map(cache -> new CaffeineCache(cache.getCacheName(), Caffeine.newBuilder().recordStats()
.expireAfterWrite(cache.getExpiredAfterWrite(), TimeUnit.SECONDS)
.maximumSize(cache.getMaximumSize())
.build()
)
)
.collect(Collectors.toList());
cacheManager.setCaches(caches);
return cacheManager;
}
}
ChartDataService.java
@Cacheable(cacheNames = "history")
public String getHistory(String currencyPair, String timeUnit, long from, long to) {
해당 method에 @Cacheable추가
cache가 적용 되었는지 보기 위해 로그 설정하기
application.yml
logging:
level:
org:
hibernate:
SQL: DEBUG
type.descriptor.sql.BasicBinder: DEBUG
참고
Spring boot 에 caffeine 캐시를 적용해보자 - 어떻게하면 일을 안 할까? (yevgnenll.me)
728x90
'Spring > Spring Boot(스프링 부트)' 카테고리의 다른 글
WebFlux test get, get with param, post, post with param (0) | 2019.01.18 |
---|---|
Optional .orElseThrow(Function) 사용법 (0) | 2019.01.10 |
spring boot cache 넣기 (0) | 2019.01.09 |
Spring Boot Field Injection 피하기 (0) | 2018.12.20 |
Spring Boot 앱 빌드하고 실행하기 with jpa, h2 (0) | 2018.12.11 |
스프링 부트 API 빌드 & 테스트 (0) | 2018.11.30 |