Guava加载缓存,通过db ulk操作定期填充缓存

时间:2018-04-04 15:37:58

标签: java caching guava google-guava-cache

由于我有一个从中获取数据的批量操作,因此我不想使用refresh()来更新单个项目,而是希望利用批量调用来定期更新缓存。

我有一些方法,因为我总是调用缓存,我想知道哪种方法是最优的。

方法1 定期调用getAll(),它调用loadAll()

LoadingCache<String, String> cache = CacheBuilder.newBuilder()
            .ticker(ticker)
            .refreshAfterWrite(5,  TimeUnit.Minut)
            .expireAfterAccess(30, TimeUnit.MINUTES)
            .build(cacheLoader);

private static final class CacheLoader extends CacheLoader<String, String> {
    @Override
    public String load(final String key) {
           return db.getItem(key);
    }
    @Override
    public ListenableFuture<String> reload(String key) {
      ListenableFutureTask<String> task = ListenableFutureTask.create(new Callable<String>() {
               public String call() {
                 return db.getItem(key);
               }
             });
             executor.execute(task);
             return task;
    } 
    @Override
    public String loadAll(final List<String> key) {
           return db.bulkGetItems(keyList);
    }

}

private class RefresherRunnable implements Runnable {
    private volatile boolean stopped = false;
    @Override
    public void run() {
        while (!stopped) {
            try {
               List<String> keys = getKeys();
                cache.getAll(keys);
            } catch (Exception e) {
              //log

            }

            final long nextSleepInterval = 1000 * 60;
            try {
                Thread.sleep(nextSleepInterval);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

方法2

只需使用Cache.asMap().putAll

即可
private class RefresherRunnable implements Runnable {
    private volatile boolean stopped = false;
    @Override
    public void run() {
        while (!stopped) {
            try {
               List<String> keys = getKeys();
               Map<String, String> keyValueMap = db.bulkGetItems(keys);
               cache.asMap().putAll(keyValueMap);
            } catch (Exception e) {
              //log

            }

            final long nextSleepInterval = 1000 * 60;
            try {
                Thread.sleep(nextSleepInterval);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

我从https://github.com/google/guava/wiki/CachesExplained#inserted-directly了解到了这一点 听起来像getAll比asMap.put()更好,所以方法1是首选,我猜?

0 个答案:

没有答案