要求懂的知識:AOP、Filter、反射(Attribute)。
如果直接使用 Polly,那么就會(huì )造成業(yè)務(wù)代碼中混雜大量的業(yè)務(wù)無(wú)關(guān)代碼。我們使用 AOP (如果不了解 AOP,請自行參考網(wǎng)上資料)的方式封裝一個(gè)簡(jiǎn)單的框架,模仿 Spring cloud 中的 Hystrix。
需要先引入一個(gè)支持.Net Core 的 AOP,我們用.Net Core 下的 AOP 框架是AspectCore(國產(chǎn),動(dòng)態(tài)織入),其他要不就是不支持.Net Core,要不就是不支持對異步方法進(jìn)行攔截 MVC Filter。
GitHub:https://github.com/dotnetcore/AspectCore-Framework
Install-Package AspectCore.Core -Version 0.5.0
這里只介紹和我們相關(guān)的用法:
1、編寫(xiě)攔截器CustomInterceptorAttribute 一般繼承自AbstractInterceptorAttribute




2、編寫(xiě)需要被代理攔截的類(lèi)
在要被攔截的方法上標注CustomInterceptorAttribute 。類(lèi)需要是public類(lèi),方法如果需要攔截就是虛方法,支持異步方法,因為動(dòng)態(tài)代理是動(dòng)態(tài)生成被代理的類(lèi)的動(dòng)態(tài)子類(lèi)實(shí)現的。


public class Person{ [CustomInterceptor] public virtual void Say(string msg) { Console.WriteLine('service calling...'+msg); }}

3、通過(guò)AspectCore創(chuàng )建代理對象




注意p指向的對象是AspectCore生成的Person的動(dòng)態(tài)子類(lèi)的對象,直接new Person是無(wú)法被攔截的。
攔截器中Invoke方法下的參數AspectContext的屬性的含義:
Implementation 實(shí)際動(dòng)態(tài)創(chuàng )建的Person子類(lèi)的對象。
ImplementationMethod就是Person子類(lèi)的Say方法
Parameters 方法的參數值。
Proxy==Implementation:當前場(chǎng)景下
ProxyMethod==ImplementationMethod:當前場(chǎng)景下
ReturnValue返回值
ServiceMethod是Person的Say方法
聯(lián)系客服