Created
March 30, 2015 14:33
-
-
Save marceloverdijk/a8ad372c55f40f302c69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.cache.Cache; | |
import com.google.common.cache.CacheStats; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.actuate.endpoint.PublicMetrics; | |
import org.springframework.boot.actuate.metrics.Metric; | |
import org.springframework.cache.CacheManager; | |
import org.springframework.stereotype.Component; | |
import org.springframework.util.Assert; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.LinkedHashSet; | |
import java.util.List; | |
@Component | |
public class CacheMetrics implements PublicMetrics { | |
private CacheManager cacheManager; | |
@Autowired | |
public CacheMetrics(CacheManager cacheManager) { | |
Assert.notNull(cacheManager, "cacheManager must not be null"); | |
this.cacheManager = cacheManager; | |
} | |
@Override | |
public Collection<Metric<?>> metrics() { | |
Collection<Metric<?>> result = new LinkedHashSet<>(); | |
List<String> cacheNames = new ArrayList<>(cacheManager.getCacheNames()); | |
Collections.sort(cacheNames); // sort cache names alphabetically | |
for (String cacheName : cacheNames) { | |
String prefix = String.format("cache.%s.", cacheName); | |
Object nativeCache = cacheManager.getCache(cacheName).getNativeCache(); | |
if (nativeCache instanceof Cache) { | |
Cache cache = (Cache) nativeCache; | |
CacheStats stats = cache.stats(); | |
result.add(new Metric<>(prefix + "size", cache.size())); | |
result.add(new Metric<>(prefix + "eviction_count", stats.evictionCount())); | |
result.add(new Metric<>(prefix + "hit_count", stats.hitCount())); | |
result.add(new Metric<>(prefix + "hit_rate", stats.hitRate())); | |
result.add(new Metric<>(prefix + "miss_count", stats.missCount())); | |
result.add(new Metric<>(prefix + "miss_rate", stats.missRate())); | |
result.add(new Metric<>(prefix + "request_count", stats.requestCount())); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment