LoginSignup
0
2

More than 1 year has passed since last update.

【Java】Caffeineでお手軽にローカルキャッシュ

Last updated at Posted at 2020-12-10

Caffeineでお手軽にローカルキャッシュ

https://github.com/ben-manes/caffeine
・DBにクエリを投げた結果をキャッシュしたい
・TTL(Timeout) が設定できる
・ローカルキャッシュなのでサーバーの設定とか要らない
・Spring で @Cacheable とかやったけど上手く動かなかったというのはまた別の話・・・(ぇ

環境

・Windows10 64bit
・Spring MVC 4
・Caffeine 2.8.8
・DIで呼び出すサービスにキャッシュをセット

Maven

        <!-- https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine -->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.8</version>
        </dependency>

SampleService

・キャッシュのキー:ここではサンプルで固定ですが、パラメータがある場合はパラメータから一意なキーを作成します

private static final String CACHE_KEY = "sampleCacheKey";

・キャッシュ本体

private static @NonNull Cache<Object, Object> sampleCache = null;

・初期設定

    @PostConstruct
    public void initSampleCache() {
        sampleCache =
                Caffeine.newBuilder()
                .maximumSize(1L)
                .expireAfterWrite(30, TimeUnit.MINUTES)
//              .recordStats()
                .build();
    }

・キャッシュを使うサービスメソッド

    @SuppressWarnings("unchecked")
    public List<Sample> selectCachedSample(int limit, int offset) {
        List<Sample> result = null;
        try {
            result = (List<Sample>)sampleCache 
                    .get(CACHE_KEY,
                            key -> sampleMapper.selectSample(limit, offset));
        }
        catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            logger.error(sw.toString());
            return null;
        }
//      logger.debug(String.format("Cache Stats:%s", sampleCache.stats()));
        return result;
    }

ログは初期設定の所と、上記のコメントを外すと出ます。
結構お手軽です。

以上、お疲れさまでした!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2