개요
spring 3.1 이후로 캐시를 쉽게 사용하는 기능을 지원한다. spring boot 의 경우 기본적으로 cache 기능이 포함되어 있다. 따로 캐시를 저장하는 서버를 둘 수도 있지만, 어플리케이션의 Local memory 를 사용할 수 도 있다.
사용법
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@EnableCaching
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
List<String> cacheNames = new ArrayList<String>();
cacheNames.add("test");
cacheNames.add("testPrice");
cacheManager.setCacheNames(cacheNames);
return cacheManager;
}
}
cacheNames 에 value 값에 해당하는 이름들을 추가할 수 있다. 이곳에 이름을 등록해야 cache를 저장하고 조회할 때 찾을 수 있다.
@Cacheable(value = "test")
public List<TestersDTO> selectAllTestList() {
List<TestersDTO> testList = testDataMapper.selectAllTestList();
List<String> testNames = new ArrayList<String>();
for (TestersDTO testDTO: propList) {
testNames.add(testDTO.getTestName());
}
return testList;
}
@Cacheable(value = "testPrice", key = "#testCode")
public TestPrice getTestPrice(String testCode) {
TestPrice testPriceResult = new TestPrice();
try {
testPriceResult = utilMapper.selectTestPrice(testCode);
} catch (Exception e) {
e.printStackTrace();
testPriceResult.setPrice("Error");
testPriceResult.setAddedPrice("Error");
}
return testPriceResult;
}
캐싱 처리를 하고 싶은 메서드에 @Cacheable 어노테이션을 등록한다.
value에 cache 이름을 매핑하고, key에는 value를 구분할 것을 넣는다. (key default 0 )
위 예제와 같이 #parameter를 넣으면 parameter에 따라 달라지는 해당 메서드의 결과값을 저장하고, 조회할 수 있다.
메서드 호출 시 value, key 에 해당하는 cache에 값이 없을 시 로직 실행 후 cache에 저장 후 결과값을 반환한다.
반대로 cache 값이 있을 시 로직을 생략하고 cache에 저장된 값을 반환한다.
이슈
java.lang.IllegalArgumentException: Cannot find cache named 'test' for Builder[public java.util.List com.test.search.searchService.selectAllTestList()] caches=[property] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'
1차 에러로그
config 에 설정한 cache 이름과 Cache 어노테이션을 호출하는 메서드의 Value 값이 달라서 발생한다. Value 값을 같도록 수정해주어 해결되었다.
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'list' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public?
2차 에러로그
Cache에서 매핑할 Paramter가 없고, 필요 없음에도 Key 값을 넣으니 에러가 발생했다. 단, 문자열 대신 숫자를 넣으니 로그는 발생하지 않았다. 아예 Parameter 가 필요 없을 시에는 Cache 어노테이션에서 Key 값을 삭제하는 것이 근본적인 해결 방법으로 보인다.
'개발 > 팁' 카테고리의 다른 글
Thymeleaf 타임리프 기본 정리 (0) | 2024.02.23 |
---|---|
Sourcetree 설치 (0) | 2024.01.17 |
JAR 파일을 실행 바이너리 파일로 만들기 (0) | 2024.01.12 |
톰캣 log 찾고 열람하는 방법 (1) | 2023.12.29 |
톰캣 버전 확인 (0) | 2023.12.28 |