使用AspectCore實現AOP模式的Redis緩存

来源:https://www.cnblogs.com/king-23100/archive/2019/11/14/11855462.html
-Advertisement-
Play Games

這次的目標是實現通過標註Attribute實現緩存的功能,精簡代碼,減少緩存的代碼侵入業務代碼。 緩存內容即為Service查詢彙總的內容,不做其他高大上的功能,提升短時間多次查詢的響應速度,適當減輕資料庫壓力。 在做之前,也去看了EasyCaching的源碼,這次的想法也是源於這裡,AOP的方式讓 ...


這次的目標是實現通過標註Attribute實現緩存的功能,精簡代碼,減少緩存的代碼侵入業務代碼。

緩存內容即為Service查詢彙總的內容,不做其他高大上的功能,提升短時間多次查詢的響應速度,適當減輕資料庫壓力。

在做之前,也去看了EasyCaching的源碼,這次的想法也是源於這裡,AOP的方式讓代碼減少耦合,但是緩存策略有限。經過考慮決定,自己實現類似功能,在之後的應用中也方便對緩存策略的擴展。

本文內容也許有點不嚴謹的地方,僅供參考。同樣歡迎各位路過的大佬提出建議。

在項目中加入AspectCore

之前有做AspectCore的總結,相關內容就不再贅述了。

在項目中加入Stackexchange.Redis

在stackexchange.Redis和CSRedis中糾結了很久,也沒有一個特別的有優勢,最終選擇了stackexchange.Redis,沒有理由。至於連接超時的問題,可以用非同步解決。

  • 安裝Stackexchange.Redis
Install-Package StackExchange.Redis -Version 2.0.601
  • 在appsettings.json配置Redis連接信息
{
    "Redis": {
        "Default": {
            "Connection": "127.0.0.1:6379",
            "InstanceName": "RedisCache:",
            "DefaultDB": 0
        }
    }
}
  • RedisClient

用於連接Redis伺服器,包括創建連接,獲取資料庫等操作

public class RedisClient : IDisposable
{
    private string _connectionString;
    private string _instanceName;
    private int _defaultDB;
    private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
    public RedisClient(string connectionString, string instanceName, int defaultDB = 0)
    {
        _connectionString = connectionString;
        _instanceName = instanceName;
        _defaultDB = defaultDB;
        _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
    }

    private ConnectionMultiplexer GetConnect()
    {
        return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
    }

    public IDatabase GetDatabase()
    {
        return GetConnect().GetDatabase(_defaultDB);
    }

    public IServer GetServer(string configName = null, int endPointsIndex = 0)
    {
        var confOption = ConfigurationOptions.Parse(_connectionString);
        return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
    }

    public ISubscriber GetSubscriber(string configName = null)
    {
        return GetConnect().GetSubscriber();
    }

    public void Dispose()
    {
        if (_connections != null && _connections.Count > 0)
        {
            foreach (var item in _connections.Values)
            {
                item.Close();
            }
        }
    }
}
  • 註冊服務

Redis是單線程的服務,多幾個RedisClient的實例也是無濟於事,所以依賴註入就採用singleton的方式。

public static class RedisExtensions
{
    public static void ConfigRedis(this IServiceCollection services, IConfiguration configuration)
    {
        var section = configuration.GetSection("Redis:Default");
        string _connectionString = section.GetSection("Connection").Value;
        string _instanceName = section.GetSection("InstanceName").Value;
        int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
        services.AddSingleton(new RedisClient(_connectionString, _instanceName, _defaultDB));
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.ConfigRedis(Configuration);
    }
}
  • KeyGenerator

創建一個緩存Key的生成器,以Attribute中的CacheKeyPrefix作為首碼,之後可以擴展批量刪除的功能。被攔截方法的方法名和入參也同樣作為key的一部分,保證Key值不重覆。

public static class KeyGenerator
{
    public static string GetCacheKey(MethodInfo methodInfo, object[] args, string prefix)
    {
        StringBuilder cacheKey = new StringBuilder();
        cacheKey.Append($"{prefix}_");
        cacheKey.Append(methodInfo.DeclaringType.Name).Append($"_{methodInfo.Name}");
        foreach (var item in args)
        {
            cacheKey.Append($"_{item}");
        }
        return cacheKey.ToString();
    }

    public static string GetCacheKeyPrefix(MethodInfo methodInfo, string prefix)
    {
        StringBuilder cacheKey = new StringBuilder();
        cacheKey.Append(prefix);
        cacheKey.Append($"_{methodInfo.DeclaringType.Name}").Append($"_{methodInfo.Name}");
        return cacheKey.ToString();
    }
}

寫一套緩存攔截器

  • CacheAbleAttribute

Attribute中保存緩存的策略信息,包括過期時間,Key值首碼等信息,在使用緩存時可以對這些選項值進行配置。

public class CacheAbleAttribute : Attribute
{
    /// <summary>
    /// 過期時間(秒)
    /// </summary>
    public int Expiration { get; set; } = 300;

    /// <summary>
    /// Key值首碼
    /// </summary>
    public string CacheKeyPrefix { get; set; } = string.Empty;

    /// <summary>
    /// 是否高可用(異常時執行原方法)
    /// </summary>
    public bool IsHighAvailability { get; set; } = true;

    /// <summary>
    /// 只允許一個線程更新緩存(帶鎖)
    /// </summary>
    public bool OnceUpdate { get; set; } = false;
}
  • CacheAbleInterceptor

接下來就是重頭戲,攔截器中的邏輯就相對於緩存的相關策略,不用的策略可以分成不同的攔截器。
這裡的邏輯參考了EasyCaching的源碼,並加入了Redis分散式鎖的應用。

public class CacheAbleInterceptor : AbstractInterceptor
{
    [FromContainer]
    private RedisClient RedisClient { get; set; }

    private IDatabase Database;

    private static readonly ConcurrentDictionary<Type, MethodInfo> TypeofTaskResultMethod = new ConcurrentDictionary<Type, MethodInfo>();

    public async override Task Invoke(AspectContext context, AspectDelegate next)
    {
        CacheAbleAttribute attribute = context.GetAttribute<CacheAbleAttribute>();

        if (attribute == null)
        {
            await context.Invoke(next);
            return;
        }

        try
        {
            Database = RedisClient.GetDatabase();

            string cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

            string cacheValue = await GetCacheAsync(cacheKey);

            Type returnType = context.GetReturnType();

            if (string.IsNullOrWhiteSpace(cacheValue))
            {
                if (attribute.OnceUpdate)
                {
                    string lockKey = $"Lock_{cacheKey}";
                    RedisValue token = Environment.MachineName;

                    if (await Database.LockTakeAsync(lockKey, token, TimeSpan.FromSeconds(10)))
                    {
                        try
                        {
                            var result = await RunAndGetReturn(context, next);
                            await SetCache(cacheKey, result, attribute.Expiration);
                            return;
                        }
                        finally
                        {
                            await Database.LockReleaseAsync(lockKey, token);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 5; i++)
                        {
                            Thread.Sleep(i * 100 + 500);
                            cacheValue = await GetCacheAsync(cacheKey);
                            if (!string.IsNullOrWhiteSpace(cacheValue))
                            {
                                break;
                            }
                        }
                        if (string.IsNullOrWhiteSpace(cacheValue))
                        {
                            var defaultValue = CreateDefaultResult(returnType);
                            context.ReturnValue = ResultFactory(defaultValue, returnType, context.IsAsync());
                            return;
                        }
                    }
                }
                else
                {
                    var result = await RunAndGetReturn(context, next);
                    await SetCache(cacheKey, result, attribute.Expiration);
                    return;
                }
            }
            var objValue = await DeserializeCache(cacheKey, cacheValue, returnType);
            //緩存值不可用
            if (objValue == null)
            {
                await context.Invoke(next);
                return;
            }
                context.ReturnValue = ResultFactory(objValue, returnType, context.IsAsync());
        }
        catch (Exception)
        {
            if (context.ReturnValue == null)
            {
                await context.Invoke(next);
            }
        }
    }

    private async Task<string> GetCacheAsync(string cacheKey)
    {
        string cacheValue = null;
        try
        {
            cacheValue = await Database.StringGetAsync(cacheKey);
        }
        catch (Exception)
        {
            return null;
        }
        return cacheValue;
    }

    private async Task<object> RunAndGetReturn(AspectContext context, AspectDelegate next)
    {
        await context.Invoke(next);
        return context.IsAsync()
        ? await context.UnwrapAsyncReturnValue()
        : context.ReturnValue;
    }

    private async Task SetCache(string cacheKey, object cacheValue, int expiration)
    {
        string jsonValue = JsonConvert.SerializeObject(cacheValue);
        await Database.StringSetAsync(cacheKey, jsonValue, TimeSpan.FromSeconds(expiration));
    }

    private async Task Remove(string cacheKey)
    {
        await Database.KeyDeleteAsync(cacheKey);
    }

    private async Task<object> DeserializeCache(string cacheKey, string cacheValue, Type returnType)
    {
        try
        {
            return JsonConvert.DeserializeObject(cacheValue, returnType);
        }
        catch (Exception)
        {
            await Remove(cacheKey);
            return null;
        }
    }

    private object CreateDefaultResult(Type returnType)
    {
        return Activator.CreateInstance(returnType);
    }

    private object ResultFactory(object result, Type returnType, bool isAsync)
    {
        if (isAsync)
        {
            return TypeofTaskResultMethod
                .GetOrAdd(returnType, t => typeof(Task)
                .GetMethods()
                .First(p => p.Name == "FromResult" && p.ContainsGenericParameters)
                .MakeGenericMethod(returnType))
                .Invoke(null, new object[] { result });
        }
        else
        {
            return result;
        }
    }
}
  • 註冊攔截器

在AspectCore中註冊CacheAbleInterceptor攔截器,這裡直接註冊了用於測試的DemoService,
在正式項目中,打算用反射註冊需要用到緩存的Service或者Method。

public static class AspectCoreExtensions
{
    public static void ConfigAspectCore(this IServiceCollection services)
    {
        services.ConfigureDynamicProxy(config =>
        {
            config.Interceptors.AddTyped<CacheAbleInterceptor>(Predicates.Implement(typeof(DemoService)));
        });
        services.BuildAspectInjectorProvider();
    }
}

測試緩存功能

  • 在需要緩存的介面/方法上標註Attribute
[CacheAble(CacheKeyPrefix = "test", Expiration = 30, OnceUpdate = true)]
public virtual DateTimeModel GetTime()
{
    return new DateTimeModel
    {
        Id = GetHashCode(),
        Time = DateTime.Now
    };
}
  • 測試結果截圖

請求介面,返回時間,並將返回結果緩存到Redis中,保留300秒後過期。

相關鏈接


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

-Advertisement-
Play Games
更多相關文章
  • 問題 在使用自定義 Ef Core 倉儲和 ABP vNext 註入的預設倉儲時,通過兩個 Repository 進行 Join 操作,提示 。這個異常信息翻譯成中文的大概意思就是,你不能使用兩個 DbContext 裡面的 DbSet 進行 Join 查詢。 如果將自定義倉儲改為 進行註入,是可以 ...
  • 某天,某部門負責人小姐姐:要在訂單中識別收貨人手機號碼歸屬地,這樣可以參考判斷該客戶是否為惡意下單。搬磚君:可以,有兩種方案; 一、網上買個API介面(需要RMB支持); 二、找個手機歸屬地庫(免費,有可能不是最新);小姐姐:申請RMB,估計領導不會簽字,那就免費的吧。搬磚君:好吧,(此時心中一萬個 ...
  • 今天在遇到一個需求的時候,需要一個字元串實現自增。是根據資料庫中一個自增的int類型的值,實現自增的。但是要加上首碼。比如,資料庫中有一個自增的值,為,2。那麼這個自增的值後面的值就位3、4、5、6、7.....100、101、102......所以我要獲得 的這個字元串就要是"S0001"、"S0 ...
  • 時區縮寫: 標準時間代碼 與GMT的偏移量 描述 NZDT +13:00 紐西蘭夏令時 IDLE +12:00 國際日期變更線,東邊 NZST +12:00 紐西蘭標準時間 NZT +12:00 紐西蘭時間 AESST +11:00 澳大利亞東部夏時制 CST(ACSST) +10:30 中澳大利亞 ...
  • 眾所周知,工欲善其事必先利其器,要想砍柴快一定得有把好刀,那麼要想代碼寫的有效率、質量高一個趁手的編輯器是必不可少的,寫代碼不可能就用系統自帶的文本編輯器(如果是大佬當我沒說),這裡我推薦各位使用微軟自家的編輯器(號稱宇宙最強的IDE Visual Studio) VS2017 下載地址:https ...
  • c#微信公眾號開發 基本設置 參考微信官方文檔 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html 開發→基本配置 公眾號開發信息 註:1.記錄好開發者密碼,會在程式中驗證過程 ...
  • 我們在開發中Json傳輸數據日益普遍,有很多關於Json字元串的序列化和反序列化的文章大多都告訴你怎麼用,但是卻不會告訴你用什麼更高效。因為有太多選擇,人們往往會陷入選擇難題。 相比.NET Framework有三種選擇而.net core下已經沒有JavaScriptSerializer,但是大家 ...
  • 例如想獲取尾碼名為.txt的文件 第一種方法獲取到的是對應的文件路徑 第二種方法可以獲取到文件的一些詳細信息 類似於"*.txt" 要與路徑中的文件名匹配的搜索字元串。這個參數可以包含有效的文本路徑和通配符(*和?)的組合人物,但它不支持正則表達式。 我是參照此路徑編寫的博客,用於自己查詢快速 ht ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...