Caffeine缓存

依赖

<!-- 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);

}

}

 五步即可完成,无需繁琐操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值