依赖
<!-- Caffeine缓存库依赖-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.5</version>
</dependency>
<!-- Spring Boot Cache Starter依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Caffeine缓存库依赖-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
工具类
public class CacheUtil {
// 创建一个缓存实例,最大容量为xxxxxx,写入后xx分钟过期
private static final Cache<String, Object> cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
// 将键值对写入缓存
public static void put(String key, Object value) {
cache.put(key, value);
}
// 从缓存中读取值
public static Object get(String key) {
return cache.getIfPresent(key);
}
// 从缓存中删除键值对
public static void invalidate(String key) {
cache.invalidate(key);
}
}
监听器工具类
public class CacheListenerExample {
private Cache<String, String> cache = Caffeine.newBuilder()
.removalListener((key, value, cause) -> {
System.out.println("Key " + key + " was removed (" + cause + ")");
})
.recordStats()
.build();
public void printStats() {
CacheStats stats = cache.stats();
System.out.println("Cache hits: " + stats.hitCount());
System.out.println("Cache misses: " + stats.missCount());
}
}
写入数据,存到Caffeine中(Service当中)
void writePolicyCache(PolicyCache policyCache);
调用Caffeine进行操作
public class PolicyCacheServiceImpl implements PolicyCacheService {
@Override
public void writePolicyCache(PolicyCache policyCache) {
// RedisTool3.set(policyCache.getApplyNo(), JSON.toJSONString(policyCache));
CacheUtil.put(policyCache.getApplyNo(), JSON.toJSONString(policyCache));
}
@Override
public PolicyCache selectByApplyNo(String applyNo) {
// String res = RedisTool3.get(applyNo);
Object res2 = CacheUtil.get(applyNo);
return JSON.parseObject(res2.toString(),PolicyCache.class);
}
}
五步即可完成,无需繁琐操作