一、引入依赖
由于使用jdk9.0更新的caffenine版本不支持,这里使用低版本caffenine
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.8.8</version> //低版本
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
二、CaffenineConfig配置文件
这里配置了名字为pic的缓存
具体其他参数自己按照业务修改
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CaffeineConfig {
private static final Logger logger = LoggerFactory.getLogger(CaffeineConfig.class);
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.registerCustomCache("pic", Caffeine.newBuilder()
.expireAfterWrite(5,TimeUnit.MINUTES)
.maximumSize(100000)
.removalListener((key, value, cause) ->
logger.info("Key {} removed due to {}", key, cause))
.build()
);
return cacheManager;
}
}
三、在service使用
1.注意依赖(实战中不小心使用原配置中swagger的注解导致失败)
import org.springframework.cache.annotation.Cacheable;
工具查看是否命中缓存
全局初始化
private final CacheManager cacheManager;
public boolean isCacheHit(int n) {
Cache cache = cacheManager.getCache("pic");
if (cache != null) {
Cache.ValueWrapper valueWrapper = cache.get(n);
return valueWrapper != null;
}
return false;
}
四、controller调用查看是否命中缓存
在mes中会返回是否命中