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   dz45693  阅读(3197)  评论(1编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示