在Dropwizard中如何使用缓存?

3

我正在运行一个服务,它与MongoDB集成以添加数据到MongoDB并处理分析查询。原始数据非常不结构化,在存储时会进行一些处理,使其变得更加规范,并存储在MongoDB集合中。这些转换是使用元数据执行的,元数据有点像这样:

{
"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的meta_data集合中,并在每个插入请求时查询它。
我想在服务启动时缓存此数据。我正在寻找一个好的缓存解决方案,在dropwizard中使用缓存仍然不是很清楚。我已经阅读了dropwizard文档,但仍需要一些帮助才能开始使用缓存。服务正在运行,dropwizard版本为0.6.2。
谢谢!
1个回答

4
最简单的方法是在您的资源中使用Guava LoadingCache。如果您想在资源级别上执行此操作,则需要向您的资源添加@Singleton注释,因为它们默认为请求范围。在资源上存储状态具有缺点,您应该了解这些缺点。
例如,我已更新Dropwizard入门指南中的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))));
    }
}

嘿@Paul,当我们说资源级别时,是否也包括在该资源中调用的任何服务。我是dropwizard的新手,必须缓存我从资源中调用的api的响应。然而,我的加载缓存不起作用。我认为这是因为它不是单例类的原因。你能帮我理解一下这是否是我的缓存不起作用的原因吗? - aru_sha4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接