redis緩存一致性延時雙刪代碼實現(xiàn)方式
redis緩存一致性延時雙刪代碼
不廢話、、、如下
1、自定義注解
/**
*@author caoyue
*延時雙刪
**/
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.METHOD)
public @interface ClearCache {
? ? boolean open() default true;
}2、刪除邏輯
/**
* @author caoyue
*/
@Component
@Aspect
@Slf4j
public class DoubleClearCacheAop {
@Autowired
private UserService userService;
//聲明一個用于延時的定時線程池代替線程sleep
ScheduledExecutorService task = new ScheduledThreadPoolExecutor(10, new BasicThreadFactory.
Builder().namingPattern("clearCache-schedule-pool-%d").build());
@Pointcut("@annotation(com.inspur.henan.uac.modules.open.util.ClearCache)")
private void clearCachePoint() {
}
@Around("clearCachePoint()")
public Object clearCacheAop(ProceedingJoinPoint proceeds) throws Throwable {
Method method = ((MethodSignature) proceeds.getSignature()).getMethod();
ClearCache annotation = method.getAnnotation(ClearCache.class);
Object proceed = null;
//如果清除注解開啟了
if (annotation.open()) {
//上下文獲取信息
IPubUser user = MsySecurityContextHolder.getUser();
if (Objects.nonNull(user)) {
//執(zhí)行清除緩存的動作
userService._clearCache(user);
//業(yè)務(wù)處理
proceed = proceeds.proceed();
//延時兩秒后再刪
task.schedule(() -> {
userService._clearCache(user);
if (log.isInfoEnabled()) {
log.info(Thread.currentThread().getName() + ":double delete cache completed");
}
}, 2L, TimeUnit.SECONDS);
} else {
proceed = proceeds.proceed();
}
}
return proceed;
}
}
redis緩存延遲雙刪問題
高并發(fā)場景使用redis作為緩存存儲數(shù)據(jù),當(dāng)數(shù)據(jù)更新時,如何保證緩存一致性,
延遲雙刪的策略:
先刪除緩存,然后更新數(shù)據(jù)庫數(shù)據(jù),休眠sleep,最后再次刪除緩存數(shù)據(jù)。
休眠的時間略微大于從數(shù)據(jù)庫查詢數(shù)據(jù)的時間。
當(dāng)讀寫分離時,考慮到主從數(shù)據(jù)同步延遲,休眠時間約1s。
休眠時間不能太大,否則會影響更新的速度。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 詳解redis緩存與數(shù)據(jù)庫一致性問題解決
- 面試常問:如何保證Redis緩存和數(shù)據(jù)庫的數(shù)據(jù)一致性
- 淺談一下如何保證Redis緩存與數(shù)據(jù)庫的一致性
- MySQL數(shù)據(jù)庫和Redis緩存一致性的更新策略
- redis分布式鎖解決緩存雙寫一致性
- redis緩存與數(shù)據(jù)庫一致性的問題及解決
- Redis解決緩存一致性問題
- Spring?Boot與Redis的緩存一致性問題解決
- Redis緩存和數(shù)據(jù)庫的數(shù)據(jù)一致性的問題解決
- Redis+Caffeine多級緩存數(shù)據(jù)一致性解決方案
- Redis 緩存雙寫一致性的解決方案
相關(guān)文章
Java Socket實現(xiàn)Redis客戶端的詳細(xì)說明
socket編程是一門技術(shù),它主要是在網(wǎng)絡(luò)通信中經(jīng)常用到.這篇文章主要介紹了如何用Java Socket實現(xiàn)一個簡單的Redis客戶端,需要的朋友可以參考下2021-05-05
一文了解發(fā)現(xiàn)并解決Redis熱key與大key問題
熱key是服務(wù)端的常見問題,本文主要介紹Redis熱key與大key問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
Redis分布式鎖python-redis-lock使用方法
這篇文章主要介紹了Redis分布式鎖python-redis-lock使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
redis哨兵模式分布式鎖實現(xiàn)與實踐方式(redisson)
這篇文章主要介紹了redis哨兵模式分布式鎖實現(xiàn)與實踐方式(redisson),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

