I have a service in running, its integrated with MongoDB to add data to MongoDB and handle analytics queries. The raw data is very unstructured and while storing its manupulated a bit brought to single level and stored in MongoDB collections. The transformation are performed using Meta-Data, meta data some what like this :
{
"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"
},
......
]
}
]
}
I have stored this Meta-Data in meta_data collection in MongoDB and query it for every insertion request.
I want to cache this data at the start of the service. I am looking for a good caching solution in dropwizard. I have went through dropwizard document but its still not that clear to me how to use cache in dropwizard.I need something to help me start using the cache. The service is running and it dropwizard version is 0.6.2.
Thanks!!!
The easiest way to do this is using a Guava LoadingCache in your resource. If you want to do this at the Resource level, you'll want to add a @Singleton annotation to your Resource, as they are Request Scoped by default. Storing state on a resource has drawbacks, and you should understand those.
For an example, I've udpated the Resource class from the Dropwizard Getting Started Guide to use a cache.
This code is the "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))));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With