끄적끄적
[spring] @Cacheable 사용하기(+ ehcache 설정) 본문
dependency 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@EnableCache 추가
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Cacheable : value에는 캐시의 이름, key 에는 어떤 값을 사용할지를 명시
주의) key값은 객체의 경우 해시코드를 사용하기때문에 이를 고려해야함
@Cacheable(value = "fileList", key = "#boardId")
public List<FileAttachment> getFileAttachment(long boardId, BoardDetail boardDetail){
//중략...
}
@CacheEvict : value가 의미하는 캐시의 해당 key 값의 캐시를 제거
allEntires=true 를 통해 해당 value의 모든 캐시를 삭제가능(탐색을 할필요 없기에 성능적 이점이 있을 수 있음)
@CacheEvict(value = "fileList",key = "#boardId")
public void updateFileList(List<FileAttachment> fileAttachmentList, BoardDTO.Update dto, long boardId, Account account ){
//중략...
}
@CachePut : 항상 캐시를 생성함
###Tip
- key="#board.boardId" 이런식으로 객체내부의 필드를 지정가능
- condition 속성을 통해 특정조건을 만족하는 값에대해서만 캐싱 가능
주의사항
- public 메소드에 대해서만 어노테이션 사용가능
- 같은 클래스의 내의 메소드가 호출하는 형태로 어노테이션 사용시 작동하지 않음(프록시 관련 문제)
따라서 아래와 같이 self-autowired 형태를 취하여 사용해야한다.
private final ApplicationContext applicationContext;
private Service self(){
return applicationContext.getBean(Service.class);
}
self.cachedMethod()
ehcache 적용하기
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("properties/cache/ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<cache name="fileList"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
'개발' 카테고리의 다른 글
[spring] @Valid와 MessageSource 사용하기 (0) | 2020.02.19 |
---|---|
[javascript] 브라우저가 크롬인지 확인하는 법 (0) | 2020.02.19 |
[spring] @Async 사용하기 (0) | 2020.02.19 |
[spring] ResponseEntityExceptionHandler를 이용한 예외처리 (0) | 2020.01.07 |
[intelij] properties 파일 한글처리 (0) | 2020.01.06 |
Comments