分散式多級緩存(本地緩存,redis緩存)

来源:https://www.cnblogs.com/tangzeqi/archive/2022/07/11/16466919.html
-Advertisement-
Play Games

一、String類及常用方法 String :字元串,使用一對""引起來表示。 1.理解String的不可變性 (1)String實現了Serializable介面:表示字元串是支持序列化的 (2)實現了Comparable介面:可以比較大小 (3)String內部定義了final char[] v ...


結構包:

 

 

 使用案例:

 

 

 實現效果:

1、基本併發的本地緩存,基於分散式輕量級鎖的redis緩存

2、熱緩存(高頻訪問持續緩存)+快速過期(本地緩存2秒,redis緩存10秒)

3、方法級別緩存清理 (@HybridCache 與@HybridChange 綁定管理緩存 )

4、基於HybridType介面的可擴展式作用域,目前已實現:全局、token

5、基於HybridLevel介面的可擴展式緩存處理,目前已實現:本地緩存、redis緩存

核心代碼包:

package com.*.server.live.core.hybridCache;

import com.*.server.live.core.hybridCache.impl.DepthLocal;
import com.*.server.live.core.hybridCache.impl.DepthRedis;

import java.lang.annotation.*;

/**
 * 功能描述:多重緩存
 * 作者:唐澤齊
 * @case @HybridCache(scope = ScopeGlobal.class)
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface HybridCache {

    /*緩存深度*/
    Class<? extends HybridLevel> depth() default DepthRedis.class;

    /*緩存廣度*/
    Class<? extends HybridType> scope();

}
@HybridCache
package com.*.server.live.core.hybridCache;

import com.*.server.live.core.hybridCache.impl.DepthRedis;

import java.lang.annotation.*;

/**
 * 功能描述:多重緩存更新
 * 作者:唐澤齊
 * @case @HybridChange(clazz = LiveStudioController.class,method = "getStudio",args = {Long.class})
 * @case @HybridChange(clazz = LiveStudioController.class,method = "getStudio",args = {})
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface HybridChange {

    /*關聯類*/
    Class<? extends Object> clazz();

    /*關聯方法*/
    String method();

    /*關聯方法入參類型*/
    Class<?>[] args();
}
@HybridChange
package com.*.server.live.core.hybridCache;

import org.aspectj.lang.ProceedingJoinPoint;

import javax.validation.constraints.NotNull;

/**
 * 功能描述:多重緩存級別
 * 作者:唐澤齊
 */
public interface HybridLevel {
    /**
     * 緩存
     * @param key 緩存key
     * @param id 混村ID
     * @param o 緩存值
     * @param self 是否執行節點
     * @param joinPoint 節點
     * @return
     * @throws Throwable
     */
    Object cache(@NotNull String key,@NotNull String id, Object o,@NotNull boolean self,@NotNull ProceedingJoinPoint joinPoint) throws Throwable;

    /**
     * 清緩存
     * @param key 緩存key
     * @param self 是否執行節點
     * @param joinPoint 節點
     * @return
     * @throws Throwable
     */
    Object del(@NotNull String key,@NotNull boolean self,@NotNull ProceedingJoinPoint joinPoint) throws Throwable;
}
HybridLevel
package com.*.server.live.core.hybridCache;

/**
 * 功能描述:多重緩存級別
 * 作者:唐澤齊
 */
public interface HybridType {
    String token();
}
HybridType
package com.*.server.live.core.hybridCache;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.util.Md5Utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 功能描述:多重緩存介面
 * 作者:唐澤齊
 */
@Aspect
@Configuration
public class HybridCacheInterceptor {
    @Resource
    ApplicationContext applicationContext;
    final static String cache = "hybridCache:";

    @Around(value = "@annotation(com.*.server.live.core.hybridCache.HybridCache)")
    public Object cache(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        HybridCache cacheAnnotation = method.getAnnotation(HybridCache.class);
        String key = getCacheKey(method);
        String id = getCacheId(method,joinPoint.getArgs());
        HybridLevel hybridLevel = applicationContext.getBean(cacheAnnotation.depth());
        return hybridLevel.cache(key, id, null, true, joinPoint);
    }

    @Around(value = "@annotation(com.*.server.live.core.hybridCache.HybridChange)")
    public Object del(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        HybridChange cacheAnnotation = method.getAnnotation(HybridChange.class);
        try {
            Method method1 = cacheAnnotation.clazz().getMethod(cacheAnnotation.method(),cacheAnnotation.args());
            HybridCache cache = method1.getAnnotation(HybridCache.class);
            String key = getCacheKey(method1);
            HybridLevel hybridLevel = applicationContext.getBean(cache.depth());
            return hybridLevel.del(key,true, joinPoint);
        } catch (Exception e) {
            return joinPoint.proceed();
        }
    }

    /*獲取緩存key*/
    private String getCacheKey(Method method) {
        return cache + method.getDeclaringClass().getSimpleName() + ":" + method.getName();
    }

    ;

    /*獲取緩存id*/
    private String getCacheId(Method method,Object[] args) {
        HybridCache cacheAnnotation = method.getAnnotation(HybridCache.class);
        HybridType hybridType = applicationContext.getBean(cacheAnnotation.scope());
        return Md5Utils.getMD5((hybridType.token() + JSON.toJSONString(args)).getBytes());
    }

    ;

}
HybridCacheInterceptor

擴展代碼包:

package com.*.server.live.core.hybridCache.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.*.server.live.core.hybridCache.HybridLevel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 功能描述:本地緩存
 * 作者:唐澤齊
 */
@Component
public class DepthLocal implements HybridLevel {
    /*自帶讀寫鎖*/
    public volatile static Cache<String, Object> localCache = CacheBuilder.newBuilder().initialCapacity(144).expireAfterAccess(2, TimeUnit.SECONDS).build();

    @Override
    public Object cache(String key, String id, Object o, boolean search, ProceedingJoinPoint joinPoint) throws Throwable {
        String keyId = key + ":" + id;
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        if (search && o == null && (o = localCache.getIfPresent(keyId)) == null) {
            synchronized (ms.getMethod()) {
                if ((o = localCache.getIfPresent(keyId)) == null) {
                    o = joinPoint.proceed();
                    localCache.put(keyId, o);
                }
            }
        }
        if (o == null) {
            o = localCache.getIfPresent(keyId);
        } else {
            localCache.put(keyId, o);
        }
        return o;
    }

    @Override
    public Object del(String key, boolean self, ProceedingJoinPoint joinPoint) throws Throwable {
        Object o = null;
        if (self) {
            o = joinPoint.proceed();
        }
        localCache.cleanUp();
        return o;
    }
}
DepthLocal
package com.*.server.live.core.hybridCache.impl;

import cn.hutool.core.util.RandomUtil;
import com.*.common.redis.service.RedisService;
import com.*.server.live.core.hybridCache.HybridLevel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 功能描述:redis緩存
 * 作者:唐澤齊
 */
@Component
public class DepthRedis implements HybridLevel {

    @Resource
    private RedisService redisService;
    @Resource
    private HybridLevel depthLocal;

    @Override
    public synchronized Object cache(String key, String id, Object o,boolean search, ProceedingJoinPoint joinPoint) throws Throwable {
        o = depthLocal.cache(key, id, o,false,joinPoint);
        String lock = getLock(key, id);
        if(search && o== null && (o=redisService.hget(key , id)) == null ) {
            for (;;) {
                if(redisService.incr(lock,1l) <= 1l && (o=redisService.hget(key , id)) == null ) {
                    try {
                        o = joinPoint.proceed();
                        redisService.hset(key , id, o, 10l);
                    } catch (Throwable e) {
                        throw e;
                    }finally {
                        redisService.del(lock);
                    }
                } else {
                    o = redisService.hget(key , id);
                }
                if(o == null) {
                    Thread.sleep(1);
                } else {
                    break;
                }
            }
        }
        if (o == null) {
            o = redisService.hget(key , id);
        } else {
            depthLocal.cache(key, id, o,false,joinPoint);
            redisService.hset(key , id, o, 10l);
        }
        return o;
    }

    @Override
    public Object del(String key,boolean self,  ProceedingJoinPoint joinPoint) throws Throwable {
        Object o = null;
        if (self) {
            o = joinPoint.proceed();
        }
        redisService.del(key);
        depthLocal.del(key,false,joinPoint);
        return o;
    }

    private String getLock(String key, String id) {
        return this.getClass().getSimpleName()+":"+key+":"+id;
    }

}
DepthRedis
package com.*.server.live.core.hybridCache.impl;

import com.*.server.live.core.hybridCache.HybridType;
import org.springframework.stereotype.Component;

/**
 * 功能描述:全局級別
 * 作者:唐澤齊
 */
@Component
public class ScopeGlobal implements HybridType {
    @Override
    public String token() {
        return "";
    }
}
ScopeGlobal
package com.*.server.live.core.hybridCache.impl;

import com.*.common.core.utils.*Util;
import com.*.server.live.core.hybridCache.HybridType;
import org.springframework.stereotype.Component;

/**
 * 功能描述:token級別
 * 作者:唐澤齊
 */
@Component
public class ScopeToken implements HybridType {
    @Override
    public String token() {
        return *Util.getCurrentTokenValue();
    }
}
ScopeToken

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文介紹 點贊 + 關註 + 收藏 = 學會了 有前端開發經驗或者用過 node 的開發者應該知道,如果需要在本地運行 js 文件,需要通過 node xxx.js 來執行。 但在執行 vue create project-name 創建 Vue 項目時,為什麼命令不是以 node 開頭呢? 這次就 ...
  • CSS的任何新特性從誕生到被瀏覽器普遍支持,要經歷漫長的周期,而CSS Houdini開放了底層介面,讓開發者直接接觸、開發原生的CSS效果,實現更為複雜、流暢的效果和動畫,無需等待,快學起來吧! ...
  • 語法嵌套規則 選擇器嵌套 例如有這麼一段css,正常CSS的寫法 .container{width:1200px; margin: 0 auto;} .container .header{height: 90px; line-height: 90px;} .container .header .lo ...
  • 詳情解釋請看下方代碼區 點擊查看代碼 @Test public void test1(){ //實例化:now()獲取當前日期、時間、日期 + 時間 LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now( ...
  • 哈嘍兄弟們,又是鞏固複習基礎知識的一天~ 今天來實現一下如何同時遍歷多個序列 一、實戰場景 實戰場景: 如何同時遍歷多個序列。 二、主要知識點 同時遍歷多個序列zip 函數 三、菜鳥實戰 馬上安排! 1、創建 python 文件 # 導入系統包 import platform # 我還給大家準備了海 ...
  • 一般學習一項技術,會先用一個最簡單的例子或最典型的例子來向大家講解入門內容,所以此文為大家介紹使用docker安裝nginx容器服務。從基礎使用的角度來講,此文幾乎涵蓋了docker最核心的內容:鏡像拉取、容器運行、埠映射、文件映射,雖然基礎但很重要,所以建議認真學習。 一、拉取鏡像 docker ...
  • <b><font size=4>一、System靜態方法</font></b> 點擊查看代碼 package com.Tang.StringDay01; import org.junit.Test; public class DateTimeTest { /* System類中的currentTim ...
  • 前言 嗨嘍,大家好呀~這裡是愛看美女的茜茜吶 代碼提供者:青燈教育-巳月 知識點: 動態數據抓包 requests發送請求 結構化+非結構化數據解析 準備工作 下麵的儘量跟我保持一致哦~不然有可能會發生報錯 💕 開發環境: python 3.8運行代碼 pycharm 2021.2輔助敲代碼 re ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...