書接上文go任務調器gocron和xxl-job 我們來看看asp.netcore5.0里面怎么使用, 非常高興有大佬們的貢獻https://github.com/NanoFabricFX/DotXxlJob, 我的xxl-job是2.2.0,按照githab上我們需要安裝DotXxlJob.Core然后准備代碼如下:
using DotXxlJob.Core; using DotXxlJob.Core.Model; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace WebApp { // 聲明一個AspNet的Middleware中間件,並擴展ApplicationBuilder,本質是攔截Post請求,解析Body中的流信息 public class XxlJobExecutorMiddleware { private readonly IServiceProvider _provider; private readonly RequestDelegate _next; private readonly XxlRestfulServiceHandler _rpcService; public XxlJobExecutorMiddleware(IServiceProvider provider, RequestDelegate next) { this._provider = provider; this._next = next; this._rpcService = _provider.GetRequiredService<XxlRestfulServiceHandler>(); } // 聲明一個中間件,並擴展ApplicationBuilder,本質是攔截Post請求,解析Body中的流信息 public async Task Invoke(HttpContext context) { string contentType = context.Request.ContentType; if ("POST".Equals(context.Request.Method, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(contentType) && contentType.ToLower().StartsWith("application/json")) { await _rpcService.HandlerAsync(context.Request, context.Response); return; } await _next.Invoke(context); } } //擴展ApplicationBuilderExtensions,可根據實際情況綁定在特殊的Url Path上 public static class ApplicationBuilderExtensions { public static IApplicationBuilder UseXxlJobExecutor(this IApplicationBuilder app) { return app.UseMiddleware<XxlJobExecutorMiddleware>(); } } //編寫JobHandler,繼承AbstractJobHandler或者直接實現接口IJobHandler,通過context.JobLogger 記錄執行過程和結果,在AdminWeb上可查看的哦 [JobHandler("demoJobHandler")] public class DemoJobHandler : AbstractJobHandler { public override Task<ReturnT> Execute(JobExecuteContext context) { context.JobLogger.Log("receive demo job handler,parameter:{0}", context.JobParameter); Console.WriteLine("receive demo job handler,parameter:{0}", context.JobParameter); return Task.FromResult(ReturnT.Success("receive:"+ context.JobParameter)); } } public class XxlJobExecutorOptions { /// <summary> /// 管理端地址,多個以;分隔 /// </summary> public string AdminAddresses { get; set; } /// <summary> /// appName自動注冊時要去管理端配置一致 /// </summary> public string AppName { get; set; } = "xxl-job-executor-dotnet"; /// <summary> /// 自動注冊時提交的地址,為空會自動獲取內網地址 /// </summary> public string SpecialBindAddress { get; set; } /// <summary> /// 綁定端口 /// </summary> public int Port { get; set; } /// <summary> /// 是否自動注冊 /// </summary> public bool AutoRegistry { get; set; } /// <summary> /// 認證票據 /// </summary> public string AccessToken { get; set; } /// <summary> /// 日志目錄,默認為執行目錄的logs子目錄下,請配置絕對路徑 /// </summary> public string LogPath { get; set; } = Path.Combine(AppContext.BaseDirectory, "./logs"); /// <summary> /// 日志保留天數 /// </summary> public int LogRetentionDays { get; set; } = 30; } }
修改Startup.cs的ConfigureServices方法添加:
services.AddXxlJobExecutor(Configuration); services.AddDefaultXxlJobHandlers();// add httpHandler; services.AddSingleton<IJobHandler, DemoJobHandler>(); // 添加自定義的jobHandler services.AddAutoRegistry(); // 自動注冊
在Configure方法添加:
//啟用XxlExecutor app.UseXxlJobExecutor();
修改:appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information" } }, "xxlJob": { "adminAddresses": "http://192.168.100.21:9080/xxl-job-admin", "appName": "xxl-job-executor-dotnet", "specialBindAddress": "192.168.100.2", "port": 5000, "autoRegistry": true, "accessToken": "", "logRetentionDays": 30 } }
同時也需要修改launchSettings.json文件 : "applicationUrl": "http://192.168.100.2:5000", 默認是http://localhost:5000, 我這里有2張網卡,不然xxl-job那邊無法訪問到指點的ip, 我這里演示的時候把程序放到兩台計算機上。
運行效果如下: