使用guava库LoadingCache缓存java pojo

使用guava库LoadingCache缓存java pojo,java,caching,guava,Java,Caching,Guava,我正在使用guava libraries LoadingCache在我的应用程序中缓存类 这是我想出的一门课 public class MethodMetricsHandlerCache { private Object targetClass; private Method method; private Configuration config; private LoadingCache<String, MethodMetricsHandler> handle

我正在使用guava libraries LoadingCache在我的应用程序中缓存类

这是我想出的一门课

public class MethodMetricsHandlerCache {

  private Object targetClass;
  private Method method;
  private Configuration config;

  private LoadingCache<String, MethodMetricsHandler> handlers = CacheBuilder.newBuilder()
  .maximumSize(1000)
  .build(
      new CacheLoader<String, MethodMetricsHandler>() {
        public MethodMetricsHandler load(String identifier) {
          return createMethodMetricsHandler(identifier);
        }
      });


  private MethodMetricsHandler createMethodMetricsHandler(String identifier) {
  return new MethodMetricsHandler(targetClass, method, config);
 }

 public void setTargetClass(Object targetClass) {
  this.targetClass = targetClass;
 }

 public void setMethod(Method method) {
  this.method = method;
 }

 public void setConfig(Configuration config) {
  this.config = config;
 }

 public MethodMetricsHandler getHandler(String identifier) throws ExecutionException {
  return handlers.get(identifier);
 }
我的问题:

这是在创建一个MethodMetricHandler类的缓存,这些类是在标识符上键入的(以前并没有使用过它,所以只是一个健全性检查)


还有更好的方法吗?如果我不缓存一个给定标识符,我将有多个相同MethodMetricHandler的实例(数百个)?

是的,它会创建MethodMetricHandler对象的缓存。这种方法通常是不错的,但是如果您描述了您的用例,我可能会说得更多,因为这种解决方案是非常不寻常的。你已经部分改造了工厂模式

同时考虑一些建议:

  • 非常奇怪的是,在运行getHandler之前需要调用3个setter
  • 由于键中没有“配置”,所以对于不同的配置和相同的targetClass和方法,您将从缓存中获得相同的对象
  • 为什么targetClass是
    对象
    。您可能希望通过
  • 您是否计划从缓存中逐出对象

我知道非常独特和奇怪的情况。库基本上会在应用程序中每次调用类时检查类元数据。缓存将在应用程序的生命周期内有效,因此如果我不缓存,可能会有n个调用,因此会有n个MethodMetricsHandler对象。无法更改进入MethodMetricsHandler实例的类。但是,我发现setter有一个问题,因为它将在多线程环境中运行。有没有关于改变设计以使其线程安全的建议?
...
private static MethodMetricsHandlerCache methodMetricsHandlerCache = new MethodMetricsHandlerCache();

...
MethodMetricsHandler handler = getMethodMetricsHandler(targetClass, method, config);

private MethodMetricsHandler getMethodMetricsHandler(Object targetClass, Method method, Configuration config) throws ExecutionException {
 String identifier = targetClass.getClass().getCanonicalName() + "." + method.getName();
 methodMetricsHandlerCache.setTargetClass(targetClass);
 methodMetricsHandlerCache.setMethod(method);
 methodMetricsHandlerCache.setConfig(config);
 return methodMetricsHandlerCache.getHandler(identifier);
}