xf 1 year ago
parent
commit
6be4c388de

+ 1 - 0
src/DataSharing.Application/DataSharing.Application.csproj

@@ -8,6 +8,7 @@
 
   <ItemGroup>
     <PackageReference Include="Hotline.Share" Version="1.0.36" />
+    <PackageReference Include="Polly.Core" Version="8.2.0" />
   </ItemGroup>
 
   <ItemGroup>

+ 76 - 36
src/DataSharing.Application/Services/SendTaskHandler.cs

@@ -1,36 +1,76 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.Extensions.Hosting;
-
-namespace DataSharing.Application.Services
-{
-    public class SendTaskHandler : ISendTaskHandler
-    {
-        public async Task SendAsync(DsSendTask sendTask, CancellationToken cancellationToken)
-        {
-
-        }
-    }
-
-    public interface ISendTaskHandler
-    {
-        Task SendAsync(DsSendTask sendTask, CancellationToken cancellationToken);
-    }
-
-    public class SendTaskService : BackgroundService
-    {
-        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
-        {
-            var count = 0;
-            while (!stoppingToken.IsCancellationRequested)
-            {
-                
-
-                await Task.Delay(1000, stoppingToken);
-            }
-        }
-    }
-}
+//using System;
+//using System.Collections.Generic;
+//using System.Linq;
+//using System.Text;
+//using System.Threading.Tasks;
+//using Consul;
+//using Microsoft.Extensions.DependencyInjection;
+//using Microsoft.Extensions.Hosting;
+//using Microsoft.Extensions.Logging;
+//using Polly.Registry;
+//using XF.Domain.Dependency;
+//using XF.Domain.Exceptions;
+
+//namespace DataSharing.Application.Services
+//{
+//    public class SendTaskHandler : ISendTaskHandler, IScopeDependency
+//    {
+//        private readonly ILogger<SendTaskHandler> _logger;
+
+//        public SendTaskHandler(ILogger<SendTaskHandler> logger)
+//        {
+//            _logger = logger;
+//        }
+
+//        public async Task SendAsync(int count, CancellationToken cancellationToken)
+//        {
+//            _logger.LogInformation($"==>执行send开始, count:{count}");
+//            var rd = Random.Shared.Next(1000, 10000);
+//            if (rd <= 5000)
+//            {
+//                throw new UserFriendlyException("执行失败");
+//            }
+
+//            await Task.Delay(rd, cancellationToken);
+
+//            _logger.LogInformation($"执行send结束, count:{count}<==");
+//        }
+//    }
+
+//    public interface ISendTaskHandler
+//    {
+//        Task SendAsync(int count, CancellationToken cancellationToken);
+//    }
+
+//    public class SendTaskService : BackgroundService
+//    {
+//        private readonly IServiceScopeFactory _serviceScopeFactory;
+
+//        public SendTaskService(IServiceScopeFactory serviceScopeFactory)
+//        {
+//            _serviceScopeFactory = serviceScopeFactory;
+//        }
+
+//        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+//        {
+//            using var scope = _serviceScopeFactory.CreateScope();
+//            var provider = scope.ServiceProvider;
+//            var pipelineProvider = provider.GetRequiredService<ResiliencePipelineProvider<string>>();
+//            var pipeline = pipelineProvider.GetPipeline(StrategyDefaults.RetryStrategy);
+//            var handler = provider.GetRequiredService<ISendTaskHandler>();
+
+//            var count = 0;
+//            while (!stoppingToken.IsCancellationRequested)
+//            {
+//                await pipeline.ExecuteAsync(async token =>
+//                {
+//                    Console.WriteLine($"execute count:{count}");
+//                    await handler.SendAsync(count, token);
+//                    count++;
+//                });
+
+//                await Task.Delay(1000, stoppingToken);
+//            }
+//        }
+//    }
+//}

+ 2 - 2
src/DataSharing.Application/Services/StrategyDefaults.cs

@@ -1,6 +1,6 @@
 namespace DataSharing.Application.Services;
 
-public class SendDefaults
+public class StrategyDefaults
 {
-    public const string 
+    public const string RetryStrategy = "RetryStrategy";
 }

+ 1 - 0
src/DataSharing.Host/DataSharing.Host.csproj

@@ -13,6 +13,7 @@
     <PackageReference Include="Mapster.DependencyInjection" Version="1.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.9" />
     <PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="7.0.14" />
+    <PackageReference Include="Polly.Extensions" Version="8.2.0" />
     <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.1.0" />
     <PackageReference Include="Serilog.Sinks.MongoDB" Version="5.3.1" />
     <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />

+ 0 - 16
src/DataSharing.Host/Properties/launchSettings.json

@@ -1,13 +1,5 @@
 {
   "$schema": "https://json.schemastore.org/launchsettings.json",
-  "iisSettings": {
-    "windowsAuthentication": false,
-    "anonymousAuthentication": true,
-    "iisExpress": {
-      "applicationUrl": "http://localhost:47038",
-      "sslPort": 0
-    }
-  },
   "profiles": {
     "http": {
       "commandName": "Project",
@@ -18,14 +10,6 @@
       "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development"
       }
-    },
-    "IIS Express": {
-      "commandName": "IISExpress",
-      "launchBrowser": true,
-      "launchUrl": "swagger",
-      "environmentVariables": {
-        "ASPNETCORE_ENVIRONMENT": "Development"
-      }
     }
   }
 }

+ 28 - 16
src/DataSharing.Host/StartupExtensions.cs

@@ -1,10 +1,13 @@
-using DataSharing.Repository.Extensions;
+using DataSharing.Application.Services;
+using DataSharing.Repository.Extensions;
 using FluentValidation;
 using FluentValidation.AspNetCore;
 using Hotline.Application;
 using Mapster;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Identity;
+using Polly;
+using Polly.Retry;
 using Serilog;
 using XF.Domain.Dependency;
 using XF.Domain.Filters;
@@ -17,6 +20,7 @@ namespace DataSharing.Host;
 internal static class StartupExtensions
 {
     const string CorsOrigins = "CorsOrigins";
+
     internal static WebApplication ConfigureServices(this WebApplicationBuilder builder)
     {
         var services = builder.Services;
@@ -61,36 +65,44 @@ internal static class StartupExtensions
         services.RegisterMapper();
 
         //mediatr
-        services.AddMediatR(d =>
-        {
-            d.RegisterServicesFromAssembly(typeof(ApplicationStartupExtensions).Assembly);
-        });
+        services.AddMediatR(d => { d.RegisterServicesFromAssembly(typeof(ApplicationStartupExtensions).Assembly); });
 
         //sqlsugar
         services.AddSqlSugar(configuration);
 
         //cache
         services.AddCache(d =>
-            {
-                var cacheConfig = configuration.GetSection("Cache").Get<CacheOptions>();
-                cacheConfig.Adapt(d);
-                d.Prefix = "DataSharing";
-                d.TopicName = "Dsharing-topic";
-            });
+        {
+            var cacheConfig = configuration.GetSection("Cache").Get<CacheOptions>();
+            cacheConfig.Adapt(d);
+            d.Prefix = "DataSharing";
+            d.TopicName = "Dsharing-topic";
+        });
 
         //validator
-        services.AddFluentValidationAutoValidation(config =>
-        {
-            config.DisableDataAnnotationsValidation = true;
-        })
+        services.AddFluentValidationAutoValidation(config => { config.DisableDataAnnotationsValidation = true; })
             .AddValidatorsFromAssembly(typeof(ApplicationStartupExtensions).Assembly);
 
         //mq
         services.AddMq(configuration);
 
+        //retry pipeline
+        services.AddResiliencePipeline(StrategyDefaults.RetryStrategy, d =>
+        {
+            d.AddRetry(new RetryStrategyOptions
+                {
+                    Delay = TimeSpan.FromSeconds(5),
+                //BackoffType = DelayBackoffType.Constant,
+                //// UseJitter = true,
+                //MaxDelay = TimeSpan.FromSeconds(10),
+                MaxRetryAttempts = 10
+            });
+                //.AddTimeout(TimeSpan.FromSeconds(5));
+        });
+
         //services.AddSingleton<IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();
         //services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
-        
+
         return builder.Build();
     }
 

+ 1 - 6
src/DataSharing/DsSendTask.cs

@@ -28,11 +28,6 @@ namespace DataSharing
         /// </summary>
         public DateTime? LastTime { get; set; }
 
-        /// <summary>
-        /// 推送成功时间
-        /// </summary>
-        public DateTime? SuccessTime { get; set; }
-
         /// <summary>
         /// 推送次数
         /// </summary>
@@ -58,7 +53,7 @@ namespace DataSharing
         /// 请求地址
         /// </summary>
         public string Path { get; set; }
-
+        
         /// <summary>
         /// 请求参数
         /// </summary>