cn.patterncat.cache.component.CacheKeysEndpoint Maven / Gradle / Ivy
package cn.patterncat.cache.component;
import cn.patterncat.cache.component.key.CacheKeysExtractorFactory;
import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.util.Pair;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by cat on 2019-03-12.
*/
@Endpoint(id = "caches-key")
public class CacheKeysEndpoint {
private final Map cacheManagers;
/**
* Create a new endpoint with the {@link CacheManager} instances to use.
*
* @param cacheManagers the cache managers to use, indexed by name
*/
public CacheKeysEndpoint(Map cacheManagers) {
this.cacheManagers = cacheManagers;
}
@ReadOperation
public List getCacheKeys(@Selector String cacheManagerName, @Selector String cacheName) {
return getCacheKeys(cacheManagerName,e -> e.equals(cacheName));
}
@ReadOperation
public Object getValueByKey(@Selector String cacheManagerName, @Selector String cacheName, @Selector String key){
CacheManager cacheManager = this.cacheManagers.get(cacheManagerName);
if(cacheManager == null){
return null;
}
Cache cache = cacheManager.getCache(cacheName);
if(cache == null){
return null;
}
Cache.ValueWrapper valueWrapper = cache.get(key);
return valueWrapper == null ? null : valueWrapper.get();
}
@DeleteOperation
public void deleteCacheEntryByKey(@Selector String cacheManagerName, @Selector String cacheName, @Selector String key){
CacheManager cacheManager = this.cacheManagers.get(cacheManagerName);
if(cacheManager == null){
return ;
}
Cache cache = cacheManager.getCache(cacheName);
if(cache == null){
return ;
}
cache.evict(key);
}
protected List getCacheKeys(String cacheManagerName, Predicate cacheNamePredicate) {
CacheManager cacheManager = this.cacheManagers.get(cacheManagerName);
return cacheManager.getCacheNames().stream()
.filter(cacheNamePredicate)
.map(cacheManager::getCache).filter(Objects::nonNull)
.map((cache) -> Pair.of(cache.getName(), CacheKeysExtractorFactory.getKeyExtractor(cache).extractKeys(cache)))
.collect(Collectors.toList());
}
}