Skip to content
This repository was archived by the owner on Nov 21, 2020. It is now read-only.

Latest commit

 

History

History
53 lines (40 loc) · 1.49 KB

cache.md

File metadata and controls

53 lines (40 loc) · 1.49 KB

Spring注解缓存

本模块简单的实现了 Google Guava CacheRedisSpring 缓存版,还没有使用过 Spring Cache 的小伙伴,可以自行谷歌了解下

创建缓存管理器

@Bean
public GuavaCacheManager guavaCacheManager() {
    // @formatter:off
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .softValues()
            .initialCapacity(128)
            .maximumSize(1024);
    // @formatter:on
    return CacheUtils.newGuavaCacheManager(cacheBuilder, "cache1", "cache2");
}
@Bean
public GuavaCacheManager guavaCacheManager() {
    Map<String, GuavaCacheCreator> creatorMap = new HashMap<>(2, 1);
    // 不同的缓存使用不同的缓存策略
    creatorMap.put("cache1", CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES));
    creatorMap.put("cache2", CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES));
    return CacheUtils.newGuavaCacheManager(creatorMap);
}

提供多种创建方式,你可以选择任意你喜欢的方式创建

开启缓存

@EnableCaching

使用注解缓存

@Cacheable(value = "cache1", key = "#root.method", cacheManager = "guavaCacheManager")

或者

@Cacheable(value = "cache2", key = "#root.args", cacheManager = "guavaCacheManager")

当然,你也可以不使用注解,直接在代码中手动缓存,使用你用到的 CacheManager 即可