ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.Net Core使用xxl-job定时任务

2022-05-15 18:04:06  阅读:516  来源: 互联网

标签:Core return job context services Net public xxl


一、下载NuGet包

NuGet:DotXxlJob.Core

二、Startup类

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // 注入xxl-job
            services.AddxxlJobs(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 注入xxl-job执行器
            app.UseXxlJobExecutor();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

二、appsettings.json配置文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "xxlJob": {
    "adminAddresses": "http://192.168.140.130:8080/xxl-job-admin", //调度服务平台的地址
    "appName": "xxl-job-dotnet", //执行器的名称,与调度平台配置的名称必须一致
    "specialBindAddress": "192.168.0.102", //被调度的服务地址
    "port": 5003, //被调度的服务端口
    "autoRegistry": true,
    "accessToken": "",
    "logRetentionDays": 30,
    "logPath ": "/LogFile"
  }
}

三、DependencyInjectionExtersion类

public static class DependencyInjectionExtersion
    {
        public static IServiceCollection AddxxlJobs(this IServiceCollection services, IConfiguration configurationSection)
        {
            services.AddXxlJobExecutor(configurationSection);
            var types = GetSubClassType(typeof(AbstractJobHandler));
            var methods = typeof(ServiceCollectionServiceExtensions).GetMethods();
            MethodInfo method = methods.FirstOrDefault(m => m.Name == "AddSingleton" && m.IsGenericMethod && m.GetGenericArguments().Length == 2);
            // 自动注册Job,请勿手动注册
            foreach (var type in types)
            {
                var registerMethod = method.MakeGenericMethod(new Type[] { typeof(IJobHandler), type });
                registerMethod.Invoke(services, new object[] { services });
            }
            services.AddAutoRegistry();
            return services;
        }
        public static List<Type> GetSubClassType(Type baseType)
        {
            var allTypes = typeof(DemoHandler).Assembly.GetTypes();
            return allTypes.Where(t => t.BaseType != null && t.BaseType.Equals(baseType)).ToList();
        }


        public static IApplicationBuilder UseXxlJobExecutor(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<XxlJobExecutorMiddleware>();
        }
    }

四、XxlJobExecutorMiddleware类

public class XxlJobExecutorMiddleware
    {
        private readonly IServiceProvider _provider;
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly XxlRestfulServiceHandler _rpcService;
        public XxlJobExecutorMiddleware(IServiceProvider provider, RequestDelegate next, ILoggerFactory loggerFactory)
        {
            this._provider = provider;
            this._next = next;
            this._rpcService = _provider.GetRequiredService<XxlRestfulServiceHandler>();
            _logger = loggerFactory.CreateLogger(this.GetType());

        }

        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);


        }
    }

 

五、DemoHandler

[JobHandler("DemoHandler")]
    public class DemoHandler: AbstractJobHandler
    {
        public async override Task<ReturnT> Execute(JobExecuteContext context)
        {
            // dosomething
            {
                // 获取xxl-job传参(根据业务需求,也可不设置参数)
                var jobParameter = context.JobParameter.GetParameter();
                if (jobParameter!=null && !string.IsNullOrWhiteSpace(jobParameter.UserName))
                {
                    // dosomething
                }

            }

            return await Task.FromResult(ReturnT.SUCCESS);
        }
    }

六、JobParameterConvert

public static class JobParameterConvert
    {
        public static JobParameter GetParameter(this string paramString)
        {
            if (string.IsNullOrEmpty(paramString)) return new JobParameter();
            return JsonConvert.DeserializeObject<JobParameter>(paramString);
        }
    }

    public class JobParameter
    {
        public string UserName { get; set; }
    }

七、xxl-job服务端配置执行器

 

 

八、xxl-job服务端配置任务

 

 查看任务执行日志

 

GitHub:https://github.com/NanoFabricFX/DotXxlJob/tree/master/samples/ASPNetCoreExecutor

参考链接:https://blog.csdn.net/weixin_33863087/article/details/93591380?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-0-93591380-blog-116107925.pc_relevant_default&spm=1001.2101.3001.4242.1&utm_relevant_index=3

 

标签:Core,return,job,context,services,Net,public,xxl
来源: https://www.cnblogs.com/sportsky/p/16273823.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有