2014-10-01 63 views
2

我有一个运行中的服务,它与MongoDB集成以向MongoDB添加数据并处理分析查询。原始数据是非结构化的,同时将其manupulated存储在一个级别并存储在MongoDB集合中。使用元数据进行改造,元数据的一些东西是这样的:在Dropwizard中使用缓存?

{ 
"DeviceCategory":"DeviceCategoryName", 
"ObjectIdentifier":"CollectionName" //Collection where document needs to be inserted 
"Node": [ 
    "node1", 
    "node2" // embeded nodes in raw data 
], 
"ExtraFields": [ //using this extra fields are added to raw data to handle queries 
    { 
     "TargetCollection": "TargetCollectionName", //collection to query for document 
     "QueryParams": [  //parameter needed to query 
      "Param1", 
      "Param2" 
     ], 
     "Keys": [ 
      { 
       "KeyToMap": "KeyName", //field to extract from returned document 
       "TargetKey": "NewKeyName" //key name to be added with value to KeyToMap 
      }, 
      ..... 
     ] 
    }, 
    { 
     "Collection": "TargetCollectionName", 
     "QueryParams": [ 
      "Param1"     
     ], 
     "Keys": [ 
      { 
       "KeyToMap": "KeyName", 
       "TargetKey": "NewKeyName" 
      }, 
      ...... 
     ] 
    } 
] 
} 

我已经存储了该元数据的收集meta_data在MongoDB中,并查询它为每一个加入请求。

我想在服务启动时缓存这些数据。我在dropwizard中寻找一个好的缓存解决方案。我已经通过dropwizard文件,但它仍然不是那么清楚如何使用dropwizard中的缓存。我需要一些帮助我开始使用缓存。该服务正在运行,它的dropwizard版本是0.6.2。

谢谢!

回答

3

最简单的方法是在资源中使用Guava LoadingCache。如果要在资源级别执行此操作,则需要为资源添加@Singleton注释,因为它们默认为请求作用域。在资源上存储状态有缺点,你应该理解这些。

例如,我已经从Dropwizard Getting Started Guide中删除Resource类以使用缓存。

该代码是 “HelloWorldResource”:

@Path("/hello-world") 
@Produces(MediaType.APPLICATION_JSON) 
@Singleton 
public class HelloWorldResource { 
    private final String template; 
    private final String defaultName; 
    private final AtomicLong counter; 

    LoadingCache<String, String> graphs = CacheBuilder.newBuilder() 
      .maximumSize(1) 
      .build(
        new CacheLoader<String, String>() { 
         public String load(String key) throws Exception { 
          // just return "bar" no matter what the key is, this is a toy example 
          return "bar"; 
         } 
        }); 

    public HelloWorldResource(String template, String defaultName) { 
     this.template = template; 
     this.defaultName = defaultName; 
     this.counter = new AtomicLong(); 
     //optionally initialize your cache here if you like.... 
    } 

    @GET 
    @Timed 
    public Saying sayHello(@QueryParam("name") Optional<String> name) throws Exception { 
     return new Saying(counter.incrementAndGet(), 
       String.format(template, graphs.get(name.or(defaultName)))); 
    } 
}