Commit a90b5b4d by zhouhaibao

[+]xxljob提交

1 parent 5d85b064
......@@ -77,6 +77,13 @@
<version>2.1.5</version>
</dependency>
<!-- xxl-job依赖,maven仓库有该依赖,不需要手动安装 -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.4.1-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
......
......@@ -43,6 +43,6 @@ public class Application implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
dynamicTaskAdd.scanAddJob();
/* dynamicTaskAdd.scanAddJob();*/
}
}
package cn.com.glsx.process.job;
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;
/**
* xxl-job config
*
* @author yazb
*/
@Configuration
public class FrameLessXxlJobConfig {
private Logger logger = LoggerFactory.getLogger(FrameLessXxlJobConfig.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;
}
/**
* 针对多网卡、容器内部署等情况,可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP;
*
* 1、引入依赖:
* <dependency>
* <groupId>org.springframework.cloud</groupId>
* <artifactId>spring-cloud-commons</artifactId>
* <version>${version}</version>
* </dependency>
*
* 2、配置文件,或者容器启动变量
* spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
*
* 3、获取IP
* String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
*/
}
\ No newline at end of file
package cn.com.glsx.process.job.xxljob;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class HelloJobHandler {
@XxlJob("demoJobHandler")
public void demoJobHandler(String param) throws Exception {
log.info("XXL-JOB, Hello World.");
}
}
package cn.com.glsx.process.job.xxljob;
import cn.com.glsx.process.util.I18nUtil;
/**
* @author xuxueli 2020-10-29 21:11:23
*/
public enum ScheduleTypeEnum {
NONE(I18nUtil.getString("schedule_type_none")),
/**
* schedule by cron
*/
CRON(I18nUtil.getString("schedule_type_cron")),
/**
* schedule by fixed rate (in seconds)
*/
FIX_RATE(I18nUtil.getString("schedule_type_fix_rate")),
/**
* schedule by fix delay (in seconds), after the last time
*/
/*FIX_DELAY(I18nUtil.getString("schedule_type_fix_delay"))*/;
private String title;
ScheduleTypeEnum(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public static ScheduleTypeEnum match(String name, ScheduleTypeEnum defaultItem){
for (ScheduleTypeEnum item: ScheduleTypeEnum.values()) {
if (item.name().equals(name)) {
return item;
}
}
return defaultItem;
}
}
package cn.com.glsx.process.job.xxljob;
import java.util.Date;
public class XxlJobInfo {
private int id; // 主键ID
private int jobGroup; // 执行器主键ID
private String jobDesc;
private Date addTime;
private Date updateTime;
private String author; // 负责人
private String alarmEmail; // 报警邮件
private String scheduleType; // 调度类型
private String scheduleConf; // 调度配置,值含义取决于调度类型
private String misfireStrategy; // 调度过期策略
private String executorRouteStrategy; // 执行器路由策略
private String executorHandler; // 执行器,任务Handler名称
private String executorParam; // 执行器,任务参数
private String executorBlockStrategy; // 阻塞处理策略
private int executorTimeout; // 任务执行超时时间,单位秒
private int executorFailRetryCount; // 失败重试次数
private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum
private String glueSource; // GLUE源代码
private String glueRemark; // GLUE备注
private Date glueUpdatetime; // GLUE更新时间
private String childJobId; // 子任务ID,多个逗号分隔
private int triggerStatus; // 调度状态:0-停止,1-运行
private long triggerLastTime; // 上次调度时间
private long triggerNextTime; // 下次调度时间
private String busKey; //业务标识
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getJobGroup() {
return jobGroup;
}
public void setJobGroup(int jobGroup) {
this.jobGroup = jobGroup;
}
public String getJobDesc() {
return jobDesc;
}
public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAlarmEmail() {
return alarmEmail;
}
public void setAlarmEmail(String alarmEmail) {
this.alarmEmail = alarmEmail;
}
public String getScheduleType() {
return scheduleType;
}
public void setScheduleType(String scheduleType) {
this.scheduleType = scheduleType;
}
public String getScheduleConf() {
return scheduleConf;
}
public void setScheduleConf(String scheduleConf) {
this.scheduleConf = scheduleConf;
}
public String getMisfireStrategy() {
return misfireStrategy;
}
public void setMisfireStrategy(String misfireStrategy) {
this.misfireStrategy = misfireStrategy;
}
public String getExecutorRouteStrategy() {
return executorRouteStrategy;
}
public void setExecutorRouteStrategy(String executorRouteStrategy) {
this.executorRouteStrategy = executorRouteStrategy;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorBlockStrategy() {
return executorBlockStrategy;
}
public void setExecutorBlockStrategy(String executorBlockStrategy) {
this.executorBlockStrategy = executorBlockStrategy;
}
public int getExecutorTimeout() {
return executorTimeout;
}
public void setExecutorTimeout(int executorTimeout) {
this.executorTimeout = executorTimeout;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public String getGlueType() {
return glueType;
}
public void setGlueType(String glueType) {
this.glueType = glueType;
}
public String getGlueSource() {
return glueSource;
}
public void setGlueSource(String glueSource) {
this.glueSource = glueSource;
}
public String getGlueRemark() {
return glueRemark;
}
public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark;
}
public Date getGlueUpdatetime() {
return glueUpdatetime;
}
public void setGlueUpdatetime(Date glueUpdatetime) {
this.glueUpdatetime = glueUpdatetime;
}
public String getChildJobId() {
return childJobId;
}
public void setChildJobId(String childJobId) {
this.childJobId = childJobId;
}
public int getTriggerStatus() {
return triggerStatus;
}
public void setTriggerStatus(int triggerStatus) {
this.triggerStatus = triggerStatus;
}
public long getTriggerLastTime() {
return triggerLastTime;
}
public void setTriggerLastTime(long triggerLastTime) {
this.triggerLastTime = triggerLastTime;
}
public long getTriggerNextTime() {
return triggerNextTime;
}
public void setTriggerNextTime(long triggerNextTime) {
this.triggerNextTime = triggerNextTime;
}
public String getBusKey() {
return busKey;
}
public void setBusKey(String busKey) {
this.busKey = busKey;
}
}
package cn.com.glsx.process.job.xxljob;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.XxlJobRemotingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class XxlJobUtil {
public static final int SUCCESS_CODE = 200;
private static String adminAddresses;
private static String appname;
private static Integer groupId;
private static String accessToken;
@Value("${xxl.job.admin.addresses}")
public void setAdminAddresses(String adminAddresses) {
XxlJobUtil.adminAddresses = adminAddresses;
}
@Value("${xxl.job.accessToken}")
public void setAccessToken(String accessToken) {
XxlJobUtil.accessToken = accessToken;
}
@Value("${xxl.job.executor.appname}")
public void setAppname(String appname) {
XxlJobUtil.appname = appname;
}
@Value("${xxl.job.executor.groupId}")
public void setGroupId(Integer groupId) {
XxlJobUtil.groupId = groupId;
}
private static final String ADD_URL = "/jobinfo/postadd";
private static final String UPDATE_URL = "/jobinfo/postupdate";
private static final String REMOVE_URL = "/jobinfo/remove";
private static final String PAUSE_URL = "/jobinfo/stop";
private static final String START_URL = "/jobinfo/start";
private static final String ADD_AND_START_URL = "/jobinfo/trigger";
private static final String FINDBYBUSKEY = "/jobinfo/findByBusKey";
private static final String GET_GROUP_ID = "/jobgroup/pageList";
private static final String LOGIN = "/login";
/**
* 添加任务
*
* @param jobInfo 任务信息
* @return {@link String} 任务id
**/
public static String add(XxlJobInfo jobInfo) {
jobInfo.setJobGroup(groupId);
jobInfo.setGlueType("BEAN");
jobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
jobInfo.setExecutorRouteStrategy("FIRST");
jobInfo.setMisfireStrategy("DO_NOTHING");
jobInfo.setScheduleType(ScheduleTypeEnum.CRON.name());
return doPost(adminAddresses + ADD_URL, jobInfo, String.class);
}
/**
* 修改执行时间
*
* @return {@link String}
**/
public static String update(XxlJobInfo jobInfo) {
return doPost(adminAddresses + UPDATE_URL, jobInfo, String.class);
}
/**
* 删除任务
*
* @param buskey 业务key
* @return {@link String}
**/
public static String remove(String buskey) {
XxlJobInfo byBusKey = findByBusKey(buskey);
if (byBusKey != null) {
return doPost(adminAddresses + REMOVE_URL + "?id=" + byBusKey.getId(), null, String.class);
}
return null;
}
/**
* 暂停任务
*
* @param buskey 业务key
* @return {@link String}
**/
public static String pause(String buskey) {
XxlJobInfo byBusKey = findByBusKey(buskey);
if (byBusKey != null) {
return doPost(adminAddresses + PAUSE_URL + "?id=" + byBusKey.getId(), null, String.class);
}
return null;
}
/**
* 开始任务
*
* @param buskey 业务key
* @return {@link String}
**/
public static String start(String buskey) {
XxlJobInfo byBusKey = findByBusKey(buskey);
if (byBusKey != null) {
return doPost(adminAddresses + START_URL + "?id=" + byBusKey.getId(), null, String.class);
}
return null;
}
/**
* 添加并启动
*
* @param buskey 业务key
* @return {@link String}
**/
public static String trigger(String buskey) {
XxlJobInfo byBusKey = findByBusKey(buskey);
if (byBusKey != null) {
return doPost(adminAddresses + ADD_AND_START_URL + "?id=" + byBusKey.getId(), null, String.class);
}
return null;
}
/**
* 根据业务id查询tigger
*
* @param busKey 任务信息
* @return {@link String}
**/
public static XxlJobInfo findByBusKey(String busKey) {
XxlJobInfo xxlJobInfo = doPost(adminAddresses + FINDBYBUSKEY + "?busKey=" + busKey + "&jobGroup=" + groupId, null, XxlJobInfo.class);
return xxlJobInfo;
}
/**
* 根据业务id查询jobGroup
*
* @return {@link String}
**/
@PostConstruct
public void findJobGroup() {
/* Map resmap = doPost(adminAddresses + GET_GROUP_ID + "?appname=" + appname, null, Map.class);
System.out.println(resmap);
Object data = resmap.get("data");
if(data!=null){
String jsonString = JSONObject.toJSONString(data);
List<Map> maps = JSONObject.parseArray(jsonString, Map.class);
if(CollectionUtils.isNotEmpty(maps)){
Map map = maps.get(0);
groupId= (Integer) map.get("id");
}
}*/
}
public static <T> T doPost(String url, Object json, Class<T> clazz) {
log.info("请求url{},请求参数{}", url, JSONObject.toJSONString(json));
ReturnT<T> returnT = XxlJobRemotingUtil.postBody(url, accessToken, 30, json, clazz);
if (returnT.getCode() != SUCCESS_CODE) {
log.info(String.format("【xxl-job】接口调用失败,错误码:%s,原因:%s",
returnT.getCode(), returnT.getMsg()));
}
return returnT.getContent();
}
}
package cn.com.glsx.process.modules.controller;
import cn.com.glsx.process.job.DynamicTaskService;
import cn.com.glsx.process.job.instance.DynamicJob;
import cn.com.glsx.process.job.xxljob.HelloJobHandler;
import cn.com.glsx.process.job.xxljob.XxlJobInfo;
import cn.com.glsx.process.job.xxljob.XxlJobUtil;
import com.glsx.plat.core.annotation.ResponseResultBody;
import com.glsx.plat.core.web.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@Tag(name = "xxljob动态任务(Demo)")
@RestController
@RequestMapping(value = "/sop/xxljob")
@ResponseResultBody
public class TestXXLJobController {
@GetMapping("/jobtest")
@Operation(summary = "动态任务添加", description = "动态任务添加")
public void addtest(@RequestParam("cron") String cron, @RequestParam("jobName") String jobName, @RequestParam("param") String param,
@RequestParam("executorHandler") String executorHandler, @RequestParam("busKey") String busKey) {
// cron表达式
XxlJobInfo jobInfo = new XxlJobInfo();
jobInfo.setExecutorParam(param);
jobInfo.setJobDesc(jobName);
jobInfo.setAuthor("admin");
jobInfo.setScheduleConf(cron);
jobInfo.setExecutorHandler(executorHandler);
jobInfo.setBusKey(busKey);
XxlJobUtil.add(jobInfo);
}
@PostMapping("/jobtestupdate")
@Operation(summary = "动态任务更新", description = "动态任务更新")
public void updatetest(@RequestParam("cron") String cron, @RequestParam("id") Integer id) {
XxlJobInfo jobInfo = new XxlJobInfo();
jobInfo.setId(id);
jobInfo.setScheduleConf(cron);
XxlJobUtil.update(jobInfo);
}
@PostMapping("/jobtestdel")
@Operation(summary = "动态任务删除", description = "动态任务删除")
public void deltest(@RequestParam("id") String id) {
XxlJobUtil.remove(id);
}
@PostMapping("/pause")
@Operation(summary = "动态任务暂停", description = "动态任务暂停")
public void pause(@RequestParam("id") String id) {
XxlJobUtil.pause(id);
}
@PostMapping("/start")
@Operation(summary = "动态任务开启", description = "动态任务开启")
public void start(@RequestParam("id") String id) {
XxlJobUtil.start(id);
}
@PostMapping("/trigger")
@Operation(summary = "动态任务触发", description = "动态任务触发")
public void trigger(@RequestParam("id") String id) {
XxlJobUtil.trigger(id);
}
@PostMapping("/findBybusKey")
@Operation(summary = "任务查询", description = "动态任务触发")
public R findBybusKey(@RequestParam("busKey") String busKey) {
return R.ok().data(XxlJobUtil.findByBusKey(busKey));
}
}
package cn.com.glsx.process.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* i18n util
*
* @author xuxueli 2018-01-17 20:39:06
*/
public class I18nUtil {
private static Logger logger = LoggerFactory.getLogger(I18nUtil.class);
private static Properties prop = null;
public static Properties loadI18nProp(){
if (prop != null) {
return prop;
}
try {
// build i18n prop
String i18n = "zh_CN";
String i18nFile = MessageFormat.format("i18n/message_{0}.properties", i18n);
// load prop
Resource resource = new ClassPathResource(i18nFile);
EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
prop = PropertiesLoaderUtils.loadProperties(encodedResource);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return prop;
}
/**
* get val of i18n key
*
* @param key
* @return
*/
public static String getString(String key) {
return loadI18nProp().getProperty(key);
}
/**
* get mult val of i18n mult key, as json
*
* @param keys
* @return
*/
public static String getMultString(String... keys) {
Map<String, String> map = new HashMap<String, String>();
Properties prop = loadI18nProp();
if (keys!=null && keys.length>0) {
for (String key: keys) {
map.put(key, prop.getProperty(key));
}
} else {
for (String key: prop.stringPropertyNames()) {
map.put(key, prop.getProperty(key));
}
}
String json = JacksonUtil.writeValueAsString(map);
return json;
}
}
package cn.com.glsx.process.util;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Jackson util
*
* 1、obj need private and set/get;
* 2、do not support inner class;
*
* @author xuxueli 2015-9-25 18:02:56
*/
public class JacksonUtil {
private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
private final static ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* bean、array、List、Map --> json
*
* @param obj
* @return json string
* @throws Exception
*/
public static String writeValueAsString(Object obj) {
try {
return getInstance().writeValueAsString(obj);
} catch (JsonGenerationException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* string --> bean、Map、List(array)
*
* @param jsonStr
* @param clazz
* @return obj
* @throws Exception
*/
public static <T> T readValue(String jsonStr, Class<T> clazz) {
try {
return getInstance().readValue(jsonStr, clazz);
} catch (JsonParseException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* string --> List<Bean>...
*
* @param jsonStr
* @param parametrized
* @param parameterClasses
* @param <T>
* @return
*/
public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) {
try {
JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
return getInstance().readValue(jsonStr, javaType);
} catch (JsonParseException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!