减少样板我有几十个像PersonDao的数据访问对象有相似的方法:方式使用番石榴缓存
Person findById(String id) {}
List<Person> search(String firstName, LastName, Page) {}
int searchCount(String firstName, LastName) {}
我已通过添加番石榴缓存,这些类的一个尝试,它是非常好的,但有很多样板。
这里做findById看在缓存第一个例子:
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);
}
如此,因为每种方法都有不同的参数和返回类型,我结束了创建一个单独的CacheLoader每个方法!
我尝试将所有内容整合到一个单一的CacheLoader中,该单元返回Object类型并接受一个Map对象,但最后我得到了很大的难看的if/else来找出调用哪个方法来加载缓存。
我正在努力寻找一种优雅的方式来为这些数据访问对象添加缓存,有什么建议吗?也许番石榴缓存不适合这种用例?
漂亮!谢谢。 – Upgradingdave
很高兴我能帮忙:) – siledh