AspectCore Retry interceptor 重试拦截器

DIConfig

接上面的例子,DiConfig我们这不需要修改

using AspectCore.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace Malema.Net;
public class DIConfig
{
    public static IServiceProvider GetServiceProvider()
    {
        var services = new ServiceCollection();

        services.AddScoped<ITestService, TestService>();
        // 注入IMemoryCache。下面的  CacheInterceptorAttribute 会用到它
        services.AddMemoryCache(); 

        //return services.BuildServiceProvider();
        return services.BuildDynamicProxyProvider();
    }
}

写一个 Retry 拦截器 RetryInterceptorAttribute

using AspectCore.DynamicProxy;
namespace Malema.Net;
public class RetryInterceptorAttribute : AbstractInterceptorAttribute
{
    private int retryCount;
    public RetryInterceptorAttribute(int retryCount)
    {
        // 在这边可以读取到attribute的参数
        this.retryCount = retryCount;
    }

    public override async Task Invoke(AspectContext context, AspectDelegate next)
    {
        var exceptions = new List<Exception>();
        for (int i = 0; i < retryCount; i++)
        {
            try
            {
                Console.WriteLine("Retry");
                await next(context);
                return;
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }

        throw new AggregateException(exceptions);
    }
}


修改我们的测试类

namespace Malema.Net;
public interface ITestService
{
    string TestCache(int age);

    void TestRetry();
}

namespace Malema.Net;
public class TestService : ITestService
{
    private bool showError = true;

    [CacheInterceptor]
    public string TestCache(int age)
    {
        Console.WriteLine("TestCache");
        return (age + 100).ToString();
    }

    [RetryInterceptor(3)]
    public void TestRetry()
    {
        if (showError)
        {
            Console.WriteLine("exception");
            showError = false;
            throw new Exception("exception");
        }
        Console.WriteLine("does not have exception");
    }
}

修改 Program.cs

using Malema.Net;
using Microsoft.Extensions.DependencyInjection;


var sp = DIConfig.GetServiceProvider();
var service = sp.GetService<ITestService>();
service.TestRetry();

Console.ReadKey();

输出

Retry
exception
Retry
does not have exception

完整的代码在https://gitee.com/malema/Examples/tree/AspectCore%2FRetry/AspectCore-Example这边可以看到 可以用下面的git命令把代码签出到本地

git clone https://gitee.com/malema/Examples
git checkout AspectCore/Retry
最近更新的
...