💯缓存方案设计
2022年1月12日约 1280 字大约 4 分钟
💯缓存方案设计

<!-- 本地缓存 -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
package com.junziln.study.order.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.junziln.study.order.domain.CaffeineCacheTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
@Configuration
public class CaffeineCacheConfig {
@Bean(name = "promotion")
public Cache<String, CaffeineCacheTest> promotionCache() {
int rnd = ThreadLocalRandom.current().nextInt(10);
return Caffeine.newBuilder()
// 设置最后一次写入经过固定时间过期
.expireAfterWrite(30 + rnd, TimeUnit.MINUTES)
// 初始的缓存空间大小
.initialCapacity(20)
// 缓存的最大条数
.maximumSize(100)
.build();
}
/*以双缓存的形式提升首页的访问性能,这个备份缓存其实运行过程中会永不过期
* 可以作为首页的降级和兜底方案 * */
@Bean(name = "promotionBak")
public Cache<String, CaffeineCacheTest> promotionCacheBak() {
int rnd = ThreadLocalRandom.current().nextInt(10);
return Caffeine.newBuilder()
// 设置最后一次访问经过固定时间过期
.expireAfterAccess(41 + rnd, TimeUnit.MINUTES)
// 初始的缓存空间大小
.initialCapacity(20)
// 缓存的最大条数
.maximumSize(100)
.build();
}
}


在这里也提到了,实现 接口 ApplicationRunner/CommandLineRunner
加载本地,和redis缓存
数据一致性
[在这里](https://www.yuque.com/junziln/redis/cdazg6gyldmg9n41?inner=KCWhm)// RefreshPromotionCache#
@Async
@Scheduled(initialDelay=5000*60,fixedDelay = 1000*60)
public void refreshCache(){
if(promotionRedisKey.isAllowLocalCache()){
log.info("检查本地缓存[promotionCache] 是否需要刷新...");
final String brandKey = promotionRedisKey.getBrandKey();
if(null == promotionCache.getIfPresent(brandKey)||null == promotionCacheBak.getIfPresent(brandKey)){
log.info("本地缓存[promotionCache] 需要刷新");
HomeContentResult result = homeService.getFromRemote();
if(null != result){
if(null == promotionCache.getIfPresent(brandKey)) {
promotionCache.put(brandKey,result);
log.info("刷新本地缓存[promotionCache] 成功");
}
promotionCacheBak.put(brandKey,result);
log.info("刷新本地缓存[promotionCacheBak] 成功");
}else{
log.warn("从远程获得[promotionCache] 数据失败");
}
}
}
}
同时也提供强制本地缓存失效,和刷新本地缓存的接口
双缓存机制:
贡献者
wangjialin