減少樣板我有幾十個像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