728x90
반응형
@Cacheable 어노테이션을 사용하여 생성한 로컬 캐시 (ehCache)를 조회하고 삭제하는 방법을 알아보겠습니다.
import org.springframework.cache.CacheManager;
@Resource
private CacheManager cacheManager;
1. Key, Value 정보 조회
1. ehcache
public ResponseEntity<Object> ehCacheValues() {
List<Map<String, String>> result = new ArrayList<>();
for (String cacheName : cacheManager.getCacheNames()) {
EhCacheCache cache = (EhCacheCache) cacheManager.getCache(cacheName);
Ehcache ehcache = cache.getNativeCache();
for (Object key : ehcache.getKeys()) {
Element element = ehcache.get(key);
if (element != null) {
result.add(Map.of(cacheName, element.toString()));
}
}
}
return ResponseEntity.ok(result);
}
2. caffeine
public ResponseEntity<Object> caffeineValues() {
Collection<String> cacheNames = cacheManager.getCacheNames();
Map<String, ConcurrentMap<Object, Object>> result = new HashMap<>(cacheNames.size());
for (String cacheName : cacheNames) {
CaffeineCache cache = (CaffeineCache) cacheManager.getCache(cacheName);
if (cache != null) {
Cache<Object, Object> nativeCache = cache.getNativeCache();
result.put(cacheName, nativeCache.asMap());
}
}
return ResponseEntity.ok(result);
}
public ResponseEntity<Object> caffeineStatInfo() {
Collection<String> cacheNames = cacheManager.getCacheNames();
List<Map<String, String>> result = new ArrayList<>(cacheNames.size());
for (String cacheName : cacheNames) {
CaffeineCache cache = (CaffeineCache) cacheManager.getCache(cacheName);
if (cache != null) {
Cache<Object, Object> nativeCache = cache.getNativeCache();
result.add(Map.of(cacheName, nativeCache.stats().toString()));
}
}
return ResponseEntity.ok(result);
}
2. local cache 삭제
1. 다건 삭제
public void clearAll() {
for (String cacheName : cacheManager.getCacheNames()) {
Objects.requireNonNull(cacheManager.getCache(cacheName)).clear();
}
}
2. 단건 삭제
public void clearTarget(String cacheName) {
Cache targetCache = cacheManager.getCache(cacheName);
targetCache.clear();
}
728x90
반응형
'spring' 카테고리의 다른 글
[Spring] JSONArray를 사용하지 않고 Ajax로 배열 list 넘기기 (2) | 2021.01.06 |
---|---|
[Spring] java/jsp에서 properties value 불러오기 (0) | 2021.01.05 |
[SpringBoot2] java config로 hikari datasource, transaction aop 설정 (0) | 2020.11.01 |
[Spring] Mockmvc에 ExceptionHandler 등록 (0) | 2020.10.31 |
[SpringBoot] Jackson JsonAlias 설정 및 x-www-form-urlencoded 문제 해결 (0) | 2020.10.31 |
댓글