본문 바로가기
spring

[Spring] local cache key, value 조회 및 삭제

by moonsiri 2020. 12. 4.
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
반응형

댓글