电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

SpringBoot整合Xxl-Job的完整步驟記錄

瀏覽:108日期:2023-04-07 11:57:16

一、下載Xxl-Job源代碼并導(dǎo)入本地并運(yùn)行

Github地址:https://github.com/xuxueli/xxl-job

中文文檔地址:https://www.xuxueli.com/xxl-job/

1.使用Idea或Eclipse導(dǎo)入

2.執(zhí)行sql腳本(紅色標(biāo)記處)

SpringBoot整合Xxl-Job的完整步驟記錄

3.運(yùn)行xxl-job-admin(xxl-job后臺(tái)管理,主要方便管理各種各樣的任務(wù))

注意:在運(yùn)行之前,需要把2的sql腳本執(zhí)行完畢,并修改數(shù)據(jù)庫連接池。

正常啟動(dòng),訪問地址為:http://localhost:8080/xxl-job-admin

效果圖,如下所示:

SpringBoot整合Xxl-Job的完整步驟記錄

用戶名默認(rèn)為admin

密碼為123456

輸入后,進(jìn)入這個(gè)界面,如圖:

SpringBoot整合Xxl-Job的完整步驟記錄

這樣就表示Xxl-Job成功運(yùn)行了。確保運(yùn)行沒問題后,就可以開始下一步。

二、添加執(zhí)行器(Xxl-Job源代碼就一個(gè)Example,可以復(fù)用過來,你也可以選擇自己新建項(xiàng)目,新建項(xiàng)目可以在Xxl-Job基礎(chǔ)上,也可以放在其它項(xiàng)目中)

1.新建一個(gè)Maven項(xiàng)目,命名為blog-xxl-job。

2.導(dǎo)入Maven依賴

<!-- https://mvnrepository.com/artifact/com.xuxueli/xxl-job-core --> <dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

3.新建application.yml配置文件并添加如下內(nèi)容

#eurekaeureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/# web portserver.port=8081# no web#spring.main.web-environment=false# log configlogging.config=classpath:logback.xml### xxl-job admin address list, such as 'http://address' or 'http://address01,http://address02'xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin### xxl-job, access tokenxxl.job.accessToken=### xxl-job executor appnamexxl.job.executor.appname=blog-xxl-job-executor### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is nullxxl.job.executor.address=### xxl-job executor server-infoxxl.job.executor.ip=xxl.job.executor.port=9999### xxl-job executor log-pathxxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler### xxl-job executor log-retention-daysxxl.job.executor.logretentiondays=30

可以不用eureka,這里我的項(xiàng)目中用到eureka所以增加該配置。

增加logback.xml配置:

<?xml version='1.0' encoding='UTF-8'?><configuration debug='false' scan='true' scanPeriod='1 seconds'> <contextName>logback</contextName> <property name='log.path' value='/data/applogs/xxl-job/xxl-job-executor-sample-springboot.log'/> <appender name='console' class='ch.qos.logback.core.ConsoleAppender'> <encoder> <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name='file' class='ch.qos.logback.core.rolling.RollingFileAppender'> <file>${log.path}</file> <rollingPolicy class='ch.qos.logback.core.rolling.TimeBasedRollingPolicy'> <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n </pattern> </encoder> </appender> <root level='info'> <appender-ref ref='console'/> <appender-ref ref='file'/> </root></configuration>

4.編寫Application類

package com.springcloud.blog.job.execute;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableEurekaClient@EnableDiscoveryClient@SpringBootApplicationpublic class BlogXxlJobExecutorApplication { public static void main(String[] args) { SpringApplication.run(BlogXxlJobExecutorApplication.class, args); }}

5.編寫Job執(zhí)行器

package com.springcloud.blog.job.execute.jobhandler;import com.xxl.job.core.biz.model.ReturnT;import com.xxl.job.core.handler.IJobHandler;import com.xxl.job.core.handler.annotation.XxlJob;import com.xxl.job.core.log.XxlJobLogger;import com.xxl.job.core.util.ShardingUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.Arrays;import java.util.concurrent.TimeUnit;/** * XxlJob開發(fā)示例(Bean模式) * <p> * 開發(fā)步驟: * 1、在Spring Bean實(shí)例中,開發(fā)Job方法,方式格式要求為 'public ReturnT<String> execute(String param)' * 2、為Job方法添加注解 '@XxlJob(value='自定義jobhandler名稱', init = 'JobHandler初始化方法', destroy = 'JobHandler銷毀方法')',注解value值對(duì)應(yīng)的是調(diào)度中心新建任務(wù)的JobHandler屬性的值。 * 3、執(zhí)行日志:需要通過 'XxlJobLogger.log' 打印執(zhí)行日志; * * @author xuxueli 2019-12-11 21:52:51 */@Componentpublic class SampleXxlJob { private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class); /** * 1、簡單任務(wù)示例(Bean模式) */ @XxlJob('demoJobHandler') public ReturnT<String> demoJobHandler(String param) throws Exception { XxlJobLogger.log('XXL-JOB, Hello World.'); for (int i = 0; i < 5; i++) { XxlJobLogger.log('beat at:' + i); TimeUnit.SECONDS.sleep(2); } return ReturnT.SUCCESS; } /** * 2、分片廣播任務(wù) */ @XxlJob('shardingJobHandler') public ReturnT<String> shardingJobHandler(String param) throws Exception { // 分片參數(shù) ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo(); XxlJobLogger.log('分片參數(shù):當(dāng)前分片序號(hào) = {}, 總分片數(shù) = {}', shardingVO.getIndex(), shardingVO.getTotal()); // 業(yè)務(wù)邏輯 for (int i = 0; i < shardingVO.getTotal(); i++) { if (i == shardingVO.getIndex()) { XxlJobLogger.log('第 {} 片, 命中分片開始處理', i); } else { XxlJobLogger.log('第 {} 片, 忽略', i); } } return ReturnT.SUCCESS; } /** * 3、命令行任務(wù) */ @XxlJob('commandJobHandler') public ReturnT<String> commandJobHandler(String param) throws Exception { String command = param; int exitValue = -1; BufferedReader bufferedReader = null; try { // command process Process process = Runtime.getRuntime().exec(command); BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream()); bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); // command log String line; while ((line = bufferedReader.readLine()) != null) { XxlJobLogger.log(line); } // command exit process.waitFor(); exitValue = process.exitValue(); } catch (Exception e) { XxlJobLogger.log(e); } finally { if (bufferedReader != null) { bufferedReader.close(); } } if (exitValue == 0) { return IJobHandler.SUCCESS; } else { return new ReturnT<String>(IJobHandler.FAIL.getCode(), 'command exit value(' + exitValue + ') is failed'); } } /** * 4、跨平臺(tái)Http任務(wù) * 參數(shù)示例: * 'url: http://www.baidu.comn' + * 'method: getn' + * 'data: contentn'; */ @XxlJob('httpJobHandler') public ReturnT<String> httpJobHandler(String param) throws Exception { // param parse if (param == null || param.trim().length() == 0) { XxlJobLogger.log('param[' + param + '] invalid.'); return ReturnT.FAIL; } String[] httpParams = param.split('n'); String url = null; String method = null; String data = null; for (String httpParam : httpParams) { if (httpParam.startsWith('url:')) { url = httpParam.substring(httpParam.indexOf('url:') + 4).trim(); } if (httpParam.startsWith('method:')) { method = httpParam.substring(httpParam.indexOf('method:') + 7).trim().toUpperCase(); } if (httpParam.startsWith('data:')) { data = httpParam.substring(httpParam.indexOf('data:') + 5).trim(); } } // param valid if (url == null || url.trim().length() == 0) { XxlJobLogger.log('url[' + url + '] invalid.'); return ReturnT.FAIL; } if (method == null || !Arrays.asList('GET', 'POST').contains(method)) { XxlJobLogger.log('method[' + method + '] invalid.'); return ReturnT.FAIL; } // request HttpURLConnection connection = null; BufferedReader bufferedReader = null; try { // connection URL realUrl = new URL(url); connection = (HttpURLConnection) realUrl.openConnection(); // connection setting connection.setRequestMethod(method); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setReadTimeout(5 * 1000); connection.setConnectTimeout(3 * 1000); connection.setRequestProperty('connection', 'Keep-Alive'); connection.setRequestProperty('Content-Type', 'application/json;charset=UTF-8'); connection.setRequestProperty('Accept-Charset', 'application/json;charset=UTF-8'); // do connection connection.connect(); // data if (data != null && data.trim().length() > 0) { DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.write(data.getBytes('UTF-8')); dataOutputStream.flush(); dataOutputStream.close(); } // valid StatusCode int statusCode = connection.getResponseCode(); if (statusCode != 200) { throw new RuntimeException('Http Request StatusCode(' + statusCode + ') Invalid.'); } // result bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), 'UTF-8')); StringBuilder result = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line); } String responseMsg = result.toString(); XxlJobLogger.log(responseMsg); return ReturnT.SUCCESS; } catch (Exception e) { XxlJobLogger.log(e); return ReturnT.FAIL; } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (connection != null) { connection.disconnect(); } } catch (Exception e2) { XxlJobLogger.log(e2); } } } /** * 5、生命周期任務(wù)示例:任務(wù)初始化與銷毀時(shí),支持自定義相關(guān)邏輯; */ @XxlJob(value = 'demoJobHandler2', init = 'init', destroy = 'destroy') public ReturnT<String> demoJobHandler2(String param) throws Exception { XxlJobLogger.log('XXL-JOB, Hello World.'); return ReturnT.SUCCESS; } public void init() { logger.info('init'); } public void destroy() { logger.info('destory'); }}

6.增加XxlJobConfig配置類

package com.springcloud.blog.job.execute.core.config;import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class XxlJobConfig { private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class); @Value('${xxl.job.admin.addresses}') private String adminAddresses; @Value('${xxl.job.accessToken}') private String accessToken; @Value('${xxl.job.executor.appname}') private String appname; @Value('${xxl.job.executor.address}') private String address; @Value('${xxl.job.executor.ip}') private String ip; @Value('${xxl.job.executor.port}') private int port; @Value('${xxl.job.executor.logpath}') private String logPath; @Value('${xxl.job.executor.logretentiondays}') private int logRetentionDays; @Bean public XxlJobSpringExecutor xxlJobExecutor() { logger.info('>>>>>>>>>>> xxl-job config init.'); XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); xxlJobSpringExecutor.setAdminAddresses(adminAddresses); xxlJobSpringExecutor.setAppname(appname); xxlJobSpringExecutor.setAddress(address); xxlJobSpringExecutor.setIp(ip); xxlJobSpringExecutor.setPort(port); xxlJobSpringExecutor.setAccessToken(accessToken); xxlJobSpringExecutor.setLogPath(logPath); xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays); return xxlJobSpringExecutor; }}

三、結(jié)合Xxl-Job后臺(tái)系統(tǒng)增加定時(shí)任務(wù)

1.配置執(zhí)行器

SpringBoot整合Xxl-Job的完整步驟記錄

執(zhí)行器地址為(與blog-xxl-job中application.yml配置文件里的執(zhí)行器地址需要保持一致,否則會(huì)注冊(cè)失敗,導(dǎo)致任務(wù)執(zhí)行不了:

SpringBoot整合Xxl-Job的完整步驟記錄

2.添加任務(wù)

SpringBoot整合Xxl-Job的完整步驟記錄

3.任務(wù)執(zhí)行成功的標(biāo)志

SpringBoot整合Xxl-Job的完整步驟記錄

四、為什么選擇Xxl-Job

當(dāng)初選擇使用Xxl-Job有這么幾個(gè)原因:

第一、團(tuán)隊(duì)里有好幾個(gè)人上一家公司或上上家公司用過。

第二、這個(gè)生態(tài)比較豐富且開源。

第三、確實(shí)非常容易上手且輕量化(輕量化的一個(gè)體現(xiàn)就是非侵入式)

到此這篇關(guān)于SpringBoot整合Xxl-Job的文章就介紹到這了,更多相關(guān)SpringBoot整合Xxl-Job內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: (中山|佛山|江门)环氧地坪漆,停车场地板漆,车库地板漆,聚氨酯地板漆-中山永旺地坪漆厂家 | UV固化机_UVLED光固化机_UV干燥机生产厂家-上海冠顶公司专业生产UV固化机设备 | 欧美日韩国产一区二区三区不_久久久久国产精品无码不卡_亚洲欧洲美洲无码精品AV_精品一区美女视频_日韩黄色性爱一级视频_日本五十路人妻斩_国产99视频免费精品是看4_亚洲中文字幕无码一二三四区_国产小萍萍挤奶喷奶水_亚洲另类精品无码在线一区 | 权威废金属|废塑料|废纸|废铜|废钢价格|再生资源回收行情报价中心-中废网 | 水平垂直燃烧试验仪-灼热丝试验仪-漏电起痕试验仪-针焰试验仪-塑料材料燃烧检测设备-IP防水试验机 | 海峰资讯 - 专注装饰公司营销型网站建设和网络营销培训 | 泥沙分离_泥沙分离设备_泥砂分离机_洛阳隆中重工机械有限公司 | 政府回应:200块在义乌小巷能买到爱情吗?——揭秘打工族省钱约会的生存智慧 | 济南玻璃安装_济南玻璃门_济南感应门_济南玻璃隔断_济南玻璃门维修_济南镜片安装_济南肯德基门_济南高隔间-济南凯轩鹏宇玻璃有限公司 | 【灵硕展览集团】展台展会设计_展览会展台搭建_展览展示设计一站式服务公司 | 安徽合肥项目申报咨询公司_安徽合肥高新企业项目申报_安徽省科技项目申报代理 | 半容积式换热器_北京浮动盘管换热器厂家|北京亿丰上达 | 压力喷雾干燥机,喷雾干燥设备,柱塞隔膜泵-无锡市闻华干燥设备有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 睿婕轻钢别墅_钢结构别墅_厂家设计施工报价 | 深圳成考网-深圳成人高考报名网| 仿清水混凝土_清水混凝土装修_施工_修饰_保护剂_修补_清水混凝土修复-德州忠岭建筑装饰工程 | 体坛网_体坛+_体坛周报新闻客户端| 船用锚链|专业锚链生产厂家|安徽亚太锚链制造有限公司 | 无锡不干胶标签,卷筒标签,无锡瑞彩包装材料有限公司 | 微型实验室真空泵-无油干式真空泵-微型涡旋耐腐蚀压缩机-思科涡旋科技(杭州)有限公司 | 换链神器官网-友情链接交换、购买交易于一体的站长平台 | 深圳市简易检测技术有限公司 | 深圳市宏康仪器科技有限公司-模拟高空低压试验箱-高温防爆试验箱-温控短路试验箱【官网】 | 西安标准厂房_陕西工业厂房_西咸新区独栋厂房_长信科技产业园官方网站 | 注塑模具_塑料模具_塑胶模具_范仕达【官网】_东莞模具设计与制造加工厂家 | 镀锌角钢_槽钢_扁钢_圆钢_方矩管厂家_镀锌花纹板-海邦钢铁(天津)有限公司 | 喷砂机厂家_自动除锈抛丸机价格-成都泰盛吉自动化喷砂设备 | 对照品_中药对照品_标准品_对照药材_「格利普」高纯中药标准品厂家-成都格利普生物科技有限公司 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库 | 西装定制/做厂家/公司_西装订做/制价格/费用-北京圣达信西装 | 反渗透水处理设备|工业零排放|水厂设备|软化水设备|海南净水设备--海南水处理设备厂家 | 喷漆房_废气处理设备-湖北天地鑫环保设备有限公司 | 免费个人pos机申请办理-移动pos机刷卡-聚合收款码办理 | 新中天检测有限公司青岛分公司-山东|菏泽|济南|潍坊|泰安防雷检测验收 | 郑州外墙清洗_郑州玻璃幕墙清洗_郑州开荒保洁-河南三恒清洗服务有限公司 | 济南宣传册设计-画册设计_济南莫都品牌设计公司 | POM塑料_PBT材料「进口」聚甲醛POM杜邦原料、加纤PBT塑料报价格找利隆塑料 | 碳刷_刷握_集电环_恒压簧_电刷厂家-上海丹臻机电科技有限公司 | 聚丙烯酰胺_阴离子_阳离子「用量少」巩义亿腾厂家直销,售后无忧 聚合甘油__盐城市飞龙油脂有限公司 | 北京中航时代-耐电压击穿试验仪厂家-电压击穿试验机 | 重庆私家花园设计-别墅花园-庭院-景观设计-重庆彩木园林建设有限公司 |