小白開學Asp.Net Core 《四》

来源:https://www.cnblogs.com/haoxiaozhang/archive/2019/07/06/11142861.html
-Advertisement-
Play Games

小白開學Asp.Net Core《四》 —— 使用AspectCore-Framework 一、AspectCore-Framework 說AspectCore-Framework不得不先談談的AOP, AOP:在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面 ...


小白開學Asp.Net Core《四》

                              —— 使用AspectCore-Framework

 

一、AspectCore-Framework

 說AspectCore-Framework不得不先談談的AOP,

  AOP:在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切麵編程,通過預編譯方式和運行期動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,是函數式編程的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。(來自於百度百科)

  AspectCore-Framework 的具體介紹就不在這裡造輪子了,下麵列出幾遍大佬們寫的文章。

二、使用

  • Nuget 安裝 Aspectcore 及相關組件

       

   具體結合Redis來說明:

  Redis採用的是CSRedis

  • Nuget CsRedis 及相關組件的安裝

 

 下麵就直接貼代碼了

  •   分散式Redis緩存
 public class DistributedCacheManager
    {
        private static IDistributedCache Instance => AspectCoreContainer.Resolve<IDistributedCache>();

        public static string Get(string key)
        {
            if (RedisHelper.Exists(key))
            {
                return RedisHelper.Get(key);
            }

            return null;
        }

        public static async Task<string> GetAsync(string key)
        {
            if (await RedisHelper.ExistsAsync(key))
            {
                var content = await RedisHelper.GetAsync(key);
                return content;
            }

            return null;
        }

        public static T Get<T>(string key)
        {
            var value = Get(key);
            if (!string.IsNullOrEmpty(value))
                return JsonConvertor.Deserialize<T>(value);
            return default(T);
        }

        public static async Task<T> GetAsync<T>(string key)
        {
            var value = await GetAsync(key);
            if (!string.IsNullOrEmpty(value))
            {
                return JsonConvertor.Deserialize<T>(value);
            }

            return default(T);
        }

        public static void Set(string key, object data, int expiredSeconds)
        {
            RedisHelper.Set(key, JsonConvertor.Serialize(data), expiredSeconds);
        }

        public static async Task<bool> SetAsync(string key, object data, int expiredSeconds)
        {
            return await RedisHelper.SetAsync(key, JsonConvertor.Serialize(data), expiredSeconds);
        }


        public static void Remove(string key) => Instance.Remove(key);

        public static async Task RemoveAsync(string key) => await Instance.RemoveAsync(key);

        public static void Refresh(string key) => Instance.Refresh(key);

        public static async Task RefreshAsync(string key) => await Instance.RefreshAsync(key);

        public static void Clear()
        {
            throw new NotImplementedException();
        }
    }
  • Aspectcore Framwork 動態代理Redis
    [AttributeUsage(AttributeTargets.Method)]
    public class RedisCacheAttribute : AbstractInterceptorAttribute
    {       
        public int Expiration { get; set; } = 10 * 60;

        public string CacheKey { get; set; } = null;

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var parameters = context.ServiceMethod.GetParameters();
            if (parameters.Any(it => it.IsIn || it.IsOut))
                await next(context);
            else
            {
                var key = string.IsNullOrEmpty(CacheKey)
                    ? new CacheKey(context.ServiceMethod, parameters, context.Parameters).GetRedisCacheKey()
                    : CacheKey;
                var value = await DistributedCacheManager.GetAsync(key);
                if (value != null)
                {
                    if (context.ServiceMethod.IsReturnTask())
                    {
                        dynamic result = JsonConvert.DeserializeObject(value,
                            context.ServiceMethod.ReturnType.GenericTypeArguments[0]);
                        context.ReturnValue = Task.FromResult(result);
                    }
                    else
                        context.ReturnValue = JsonConvert.DeserializeObject(value, context.ServiceMethod.ReturnType);
                }
                else
                {
                    await context.Invoke(next);
                    dynamic returnValue = context.ReturnValue;
                    if (context.ServiceMethod.IsReturnTask())
                        returnValue = returnValue.Result;
                    await DistributedCacheManager.SetAsync(key, returnValue, Expiration);
                }
            }
        }
    }
  • CSRedis 服務註冊
public static IServiceCollection UseCsRedisClient(this IServiceCollection services, params string[] redisConnectionStrings)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (redisConnectionStrings == null || redisConnectionStrings.Length == 0)
                throw new ArgumentNullException(nameof(redisConnectionStrings));
            CSRedisClient redisClient;
            if (redisConnectionStrings.Length == 1)
                //單機模式
                redisClient = new CSRedisClient(redisConnectionStrings[0]);
            else
                //集群模式
                redisClient = new CSRedisClient(NodeRule: null, connectionStrings: redisConnectionStrings);
            //初始化 RedisHelper
            RedisHelper.Initialization(redisClient);
            //註冊mvc分散式緩存
            services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
            return services;
        }
  • .Net Core Startup.cs 中註冊服務
   var redisConnectionString = Configuration.GetConnectionString("Redis");
            //啟用Redis
            services.UseCsRedisClient(redisConnectionString);

 return AspectCoreContainer.BuildServiceProvider(services);//接入AspectCore.Injector
  • 具體使用
    • 簡單的直接在Controller中使用 

            

    •  在服務中使用

         

 

三、補充說明

  1、Redis 客戶端安裝本文預設都已安裝

       2、一定要在Startup.cs 的 ConfigureServices 方法中進行服務的註冊,並使用 return AspectCoreContainer.BuildServiceProvider(services); 讓AspectCore 接管,不是Aspectcore 是攔截不了的

       3、按照Aspectcore 的官方文檔來說,需要加特性的方法必須是虛方法,也就是必須加virtual 修飾。不然不會被調用

       4、本文只是用Redis緩存來說名使用AOP(Aspectcore Framwork)的一方面,並不是說只能用於 Redis ,其他的(如 日誌記錄等)都可以使用的

       5、代碼源碼全部在Github上

 

(本人堅信:學習是由淺到深的過程,先打基礎)

    不喜勿噴!謝謝!

  GitHub地址: https://github.com/AjuPrince/Aju.Carefree


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

-Advertisement-
Play Games
更多相關文章
  • 世界是物質的,物質是運動的,運動是有規律的,規律是可以被認識的 二項式反演 $$ g_n=\sum_{i=0}^n \binom{n}if_i\Rightarrow f_n=\sum_{i=0}^n( 1)^{n i}\binom{n}ig_i $$ 證明如下 $$ \begin{aligned} ...
  • 博主最近在學習加法器、乘法器、IEEE的浮點數標準,作為數字IC的基礎。當看到booth編碼的乘法器時,對booth編碼不是很理解,然後在網上找各種理解,終於豁然開朗。現將一個很好的解釋分享給大家,希望能對大家有所幫助。 首先,看看這幾個公式: 可以證明的是,這三個公式是相等的,一個有符號的二進位數 ...
  • FileInputStream : 輸入流 int available() : 一次讀取所有的位元組數 read() : 將文件上的位元組讀取到記憶體的數組中 FileOutputStream : 輸出流 write(byte[] b) : 將位元組數組中的位元組數據寫到文件上 緩衝區會在記憶體中創建一個819 ...
  • 好久沒有更新博客了,都有點對不起這個賬號了。這次跟大家分享的是一種編程思路,沒什麼技術含量,但也許能幫得到你。 我們經常會在程式程式中用到 Sleep 這個方法。Sleep 方法用起來非常簡單,但是有個問題,就是如果 Sleep 時間過長,突然想結束 Sleep,似乎沒有什麼好的辦法,至少目前我是不 ...
  • 在非同步轉同步時,使用不當容易造成死鎖(程式卡死) 看如下案例: 有一個非同步方法 在執行如上非同步方法時,嘗試將其轉換為同步方法 按照官方文檔《使用任務簡化非同步編程》,TaskCompletionSource使用步驟: 但是,以上邏輯執行時,界面會卡死!卡死效果如下,卡死的時候點擊界面其它按鈕無任何反應 ...
  • 本文通過TaskCompletionSource,實現非同步轉同步 首先有一個非同步方法,如下非同步任務延時2秒後,返回一個結果 如何使用TaskCompletionSource將此非同步方法轉成同步呢? TaskCompletionSource使用步驟: 測試結果: 關鍵字:非同步轉同步,TaskCompl ...
  • 系列章節 GRPC與.net core GRPC截止時間與元數據 GRPC與netcore Identity GRPC與netcore IdentityServer4 概述 GRPC的數據交互模式有: 1.單項RPC,最簡單的數據交換方式,客戶端發出單個請求,收到單個響應 2.服務端流式RPC,是在 ...
  • 運行結果: ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...