基本的使用方式可以去GitHub上看,这里只介绍如和与polly联合起来使用,要达到这样一个目的
HelloAsync有可能会抛异常,若执行失败就降级执行HelloFallbackAsync 方法
注意 方法标注[HystrixCommand]并且是 virtual 标注
创建拦截器
[AttributeUsage(AttributeTargets.Method)]
public class HystrixCommandAttribute:AbstractInterceptorAttribute
{
private string fallbackMethod;
public HystrixCommandAttribute(string fallbackMethod)
{
this.fallbackMethod = fallbackMethod;
}
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
try
{
await next(context);
}
catch (Exception)
{
Console.WriteLine("出错");
//1获得降级方法
var fallback = context.Implementation.GetType().GetMethod(fallbackMethod);
//2调用降级方法
var returnVal =fallback.Invoke(context.Implementation, context.Parameters);
//3把降级方法的返回直返回
context.ReturnValue = returnVal;
//throw;
}
}
}
编写需要被代理拦截的类
public class Person{
[HystrixCommand(nameof(HelloFallbackAsync))]
public virtual async Task<string> HelloAsync(string name){
Console.WriteLine("name" +name);
throw new Exception("i am ex");
return "ok";
}
public virtual async Task<string> HelloFallbackAsync(string name){
Console.WriteLine("执行失败" +name);
return "fail";
}
}
创建
ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();
using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())
{
var p = proxyGenerator.CreateClassProxy<Person>();
var re = p.HelloAsync("rup").Result;
Console.WriteLine(re);
}