I have dozens of data access objects like PersonDao with methods like:
Person findById(String id) {}
List<Person> search(String firstName, LastName, Page) {}
int searchCount(String firstName, LastName) {}
I've experimented by adding guava cache with one of these classes and it's really nice, but there's a lot of boilerplate.
Here's an example of making findById look in the cache first:
private final LoadingCache<String, Person> cacheById = CacheBuilder.newBuilder()
.maximumSize(maxItemsInCache)
.expireAfterWrite(cacheExpireAfterMinutes, TimeUnit.MINUTES)
.build(new CacheLoader<String, Person>() {
public Person load(String key) {
return findByIdNoCache(key);
});
//.... and update findById to call the cache ...
@Override
public Person findById(String id) {
return cacheById.getUnchecked(id);
}
So, because each method has different params and return types, I end up created a separate cacheLoader for every method!
I tried consolidating everything into a single CacheLoader that returns Object type and accepts a Map of objects, but then I end up with big ugly if/else to figure out which method to call to load the cache.
I'm struggling to find an elegant way to add caching to these data access objects, any suggestions? Maybe guava cache isn't meant for this use case?