使用CaffeineCache来实现spring cache的缓存定时刷新
一、背景
最近在使用spring的@Cacheable注解时发现无法做到设置定时刷新时间,找了一些资料,采用CaffeineCache实现了一个demo。
二、具体代码实现
1、config配置
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.ArrayList;
import java.util.concurrent.TimeUnit;@Configuration
@Slf4j
@EnableCaching
public class CaffeineCacheConfig {private static final int DEFAULT_MAXSIZE = 100;private static final int DEFAULT_TTL = 600;public enum HadesInsightCache {//这里相当于将缓存的key值注册进来test1(60, 100),test2(3600, 100),test3(300, 100),test4(300, 100);HadesInsightCache() {}HadesInsightCache(int ttl) {this.ttl = ttl;}HadesInsightCache(int ttl, int maxSize) {this.ttl = ttl;this.maxSize = maxSize;}/*** 最大数量*/private int maxSize = DEFAULT_MAXSIZE;/*** 过期时间*/private int ttl = DEFAULT_TTL;public int getMaxSize() {return maxSize;}public int getTtl() {return ttl;}}@Beanpublic CacheManager createCacheManager() {log.info("cache manager init...");SimpleCacheManager cacheManager = new SimpleCacheManager();ArrayList caches = new ArrayList<>();for (HadesInsightCache c : HadesInsightCache.values()) {caches.add(new CaffeineCache(c.name(),Caffeine.newBuilder().expireAfterWrite(c.getTtl(), TimeUnit.SECONDS).maximumSize(c.getMaxSize()).build()));}cacheManager.setCaches(caches);return cacheManager;}
}
2、具体使用
@Cacheable(value = "test1", key = "#param", sync = true)public String getResult(String param) {return param;}
其中value值填写config中注册的值,key值即参数,若无参数可不填,sync为是否同步加载
三、补充
1、CaffeineCache为本地缓存,若作为集群公共缓存,可采用redis来做缓存。
2、考虑后续采用自定义注解,实现注解中直接添加过期时间。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
