asp.netcore5.0使用xxl-job

书接上文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, 我这里演示的时候把程序放到两台计算机上。

运行效果如下:

 

posted on 2021-02-04 23:05  dz45693  阅读(3150)  评论(1编辑  收藏  举报

导航