使用 CacheUtils 整合 caffeine 和 redis 实现的两级缓存

配置类 CacheNameConfig

package com.litongjava.tio.web.hello.config;

import java.util.Collection;

import org.redisson.api.RedissonClient;

import com.litongjava.jfinal.aop.Aop;
import com.litongjava.jfinal.aop.annotation.Bean;
import com.litongjava.jfinal.aop.annotation.Configuration;
import com.litongjava.tio.utils.cache.CacheName;
import com.litongjava.tio.utils.cache.CacheNameService;
import com.litongjava.tio.utils.cache.caffeineredis.CaffeineRedisCacheFactory;
import com.litongjava.tio.utils.time.Time;

@AConfiguration
public class CacheNameConfig {

  @ABean
  public CacheNameService register() {
    //设置CacheName
    CacheName demo = new CacheName("demo", null, Time.MINUTE_1 * 10);
    //将CacheName添加到CacheNameService
    CacheNameService cacheNameService = new CacheNameService();
    cacheNameService.add(demo);

    //将redissonClient添加到CaffeineRedisCacheFactory
    RedissonClient redissonClient = Aop.get(RedissonClient.class);
    CaffeineRedisCacheFactory.INSTANCE.init(redissonClient);

    //注册cacheName
    Collection<CacheName> names = cacheNameService.cacheNames();
    for (CacheName cacheName : names) {
      //CaffeineCacheFactory.INSTANCE.register(cacheName);
      //RedisCacheFactory.INSTANCE.register(cacheName);
      CaffeineRedisCacheFactory.INSTANCE.register(cacheName);
    }
    return cacheNameService;
  }
}

测试类 CacheCaffeineRedisTestController

package com.litongjava.tio.web.hello.AController;

import com.litongjava.tio.http.server.annotation.RequestPath;
import com.litongjava.tio.utils.cache.CacheUtils;
import com.litongjava.tio.utils.cache.FirsthandCreater;
import com.litongjava.tio.utils.cache.ICache;
import com.litongjava.tio.utils.cache.caffeineredis.CaffeineRedisCacheFactory;

import lombok.extern.slf4j.Slf4j;

@RequestPath("/cache/caffeine/redis")
@Slf4j
public class CacheCaffeineRedisTestController {

  public Object test() {
    // firsthandCreater用户查询数据库
    FirsthandCreater<String> firsthandCreater = new FirsthandCreater<String>() {
      @Override
      public String create() {
        log.info("查询数据库");
        return "index";
      }
    };

    String cacheName = "demo";
    ICache cache = CaffeineRedisCacheFactory.INSTANCE.getCache(cacheName);
    String key = "key";
    boolean putTempToCacheIfNull = false;
    String value = CacheUtils.get(cache, key, putTempToCacheIfNull, firsthandCreater);
    return value;
  }
}

访问 http://localhost/cache/caffeine/redis/test 查看测试结果