Solon

六、缓存类型的配置切换和二级缓存应用

</> markdown

为了切换,需要把可能用到的缓存插件都引入:

驱动类型插件说明
localsolon.data这个不用单独引入(很多插件都会带上它)
redissolon.cache.jedisjedis 适配插件
redissolon.cache.redissonredisson 适配插件
memcachedsolon.cache.spymemcachedmemcached 适配插件

1、根据缓存类型切换

通过“driverType”属性申明,进而切换。示例:

demo.cache1:
  driverType: "local"

#切换为 memcached
#demo.cache1:
#  driverType: "memcached" #驱动类型
#  keyHeader: "demo" #默认为 ${solon.app.name} ,可不配置
#  defSeconds: 30 #默认为 30,可不配置
#  server: "localhost:6379"
#  password: "" #默认为空,可不配置

使用 CacheServiceSupplier,自动根据配置获取缓存服务:

@Configuration
public class Demo1Config {
    @Bean
    public CacheService cahce1(@Inject("${demo1.cache}") CacheServiceSupplier supplier) {
        return supplier.get();
    }
}

2、二级缓存的使用

@Configuration
public class Demo2Config {
    @Bean
    public CacheService cahce1(@Inject("${demo1.cache}") CacheServiceSupplier supplier) {
        CacheService cacheService = supplier.get();

        if (cacheService instanceof LocalCacheService) {
            //如果是本地缓存,直接返回
            return cacheService;
        } else {
            //尝试构建二级缓存,且缓冲5秒(1级为本地;2级为配置的)
            LocalCacheService local = new LocalCacheService();
            SecondCacheService tmp = new SecondCacheService(local, cacheService, 5);

            return tmp;
        }
    }
}

缓冲啥意思?当本地没有、远程有时,从远程拿缓存,在本地存5秒时间。称之缓冲。(否则,每次要去远程拿)