fix(): 代码规范更改

boot3.0
dongzeliang 2025-01-16 17:46:00 +08:00
parent 4b536f9777
commit 989cef6f65
26 changed files with 221 additions and 135 deletions

View File

@ -15,7 +15,8 @@ public class MybatisPlusConfig {
@Bean @Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() { public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加 // 如果配置多个插件, 切记分页最后添加
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor; return interceptor;
} }
} }

View File

@ -338,12 +338,16 @@ public final class HTMLFilter {
final List<String> paramNames = new ArrayList<>(); final List<String> paramNames = new ArrayList<>();
final List<String> paramValues = new ArrayList<>(); final List<String> paramValues = new ArrayList<>();
while (m2.find()) { while (m2.find()) {
paramNames.add(m2.group(1)); // ([a-z0-9]+) // ([a-z0-9]+)
paramValues.add(m2.group(3)); // (.*?) paramNames.add(m2.group(1));
// (.*?)
paramValues.add(m2.group(3));
} }
while (m3.find()) { while (m3.find()) {
paramNames.add(m3.group(1)); // ([a-z0-9]+) // ([a-z0-9]+)
paramValues.add(m3.group(3)); // ([^\"\\s']+) paramNames.add(m3.group(1));
// ([^\"\\s']+)
paramValues.add(m3.group(3));
} }
String paramName, paramValue; String paramName, paramValue;
@ -454,8 +458,10 @@ public final class HTMLFilter {
// validate entities throughout the string // validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s); Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find()) { while (m.find()) {
final String one = m.group(1); // ([^&;]*) // ([^&;]*)
final String two = m.group(2); // (?=(;|&|$)) final String one = m.group(1);
// (?=(;|&|$))
final String two = m.group(2);
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
} }
m.appendTail(buf); m.appendTail(buf);

View File

@ -289,8 +289,8 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
*/ */
@Override @Override
public boolean updateRoleStatus (SysRole role) { public boolean updateRoleStatus (SysRole role) {
boolean updateResult = updateById(role); // 通过 roleId 更新角色信息 // 通过 roleId 更新角色信息
return updateResult; return updateById(role);
} }
/** /**
@ -303,7 +303,8 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public boolean authDataScope (SysRole role) { public boolean authDataScope (SysRole role) {
// 修改角色信息 // 修改角色信息
boolean updateResult = updateById(role); // 通过 roleId 更新角色信息 // 通过 roleId 更新角色信息
boolean updateResult = updateById(role);
// 删除角色与部门关联 // 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId()); roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息(数据权限) // 新增角色和部门信息(数据权限)
@ -332,7 +333,8 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
// 使用MyBatis-Plus的saveBatch方法批量插入角色与菜单的关联关系 // 使用MyBatis-Plus的saveBatch方法批量插入角色与菜单的关联关系
boolean saveResult = roleMenuMapper.saveBatch(list); boolean saveResult = roleMenuMapper.saveBatch(list);
return saveResult ? list.size() : 0; // 返回成功插入的数量 // 返回成功插入的数量
return saveResult ? list.size() : 0;
} }
/** /**

View File

@ -46,18 +46,23 @@ public class JobInfoController {
public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) { public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) {
// 枚举-字典 // 枚举-字典
model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values()); // 路由策略-列表 // 路由策略-列表
model.addAttribute("GlueTypeEnum", GlueTypeEnum.values()); // Glue类型-字典 model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values());
model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values()); // 阻塞处理策略-字典 // Glue类型-字典
model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values()); // 调度类型 model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());
model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values()); // 调度过期策略 // 阻塞处理策略-字典
model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values());
// 调度类型
model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values());
// 调度过期策略
model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values());
// 执行器列表 // 执行器列表
List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll(); List<XxlJobGroup> jobGroupList1 = xxlJobGroupDao.findAll();
// filter group // filter group
List<XxlJobGroup> jobGroupList = PermissionInterceptor.filterJobGroupByRole(request, jobGroupList_all); List<XxlJobGroup> jobGroupList = PermissionInterceptor.filterJobGroupByRole(request, jobGroupList1);
if (jobGroupList==null || jobGroupList.size()==0) { if (jobGroupList==null || jobGroupList.isEmpty()) {
throw new XxlJobException(I18nUtil.getString("jobgroup_empty")); throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
} }

View File

@ -94,13 +94,13 @@ public class JobLogController {
@RequestParam(required = false, defaultValue = "10") int length, @RequestParam(required = false, defaultValue = "10") int length,
int jobGroup, int jobId, int logStatus, String filterTime) { int jobGroup, int jobId, int logStatus, String filterTime) {
// valid permission // valid permission 仅管理员支持查询全部;普通用户仅支持查询有权限的 jobGroup
PermissionInterceptor.validJobGroupPermission(request, jobGroup); // 仅管理员支持查询全部;普通用户仅支持查询有权限的 jobGroup PermissionInterceptor.validJobGroupPermission(request, jobGroup);
// parse param // parse param
Date triggerTimeStart = null; Date triggerTimeStart = null;
Date triggerTimeEnd = null; Date triggerTimeEnd = null;
if (filterTime!=null && filterTime.trim().length()>0) { if (filterTime!=null && !filterTime.trim().isEmpty()) {
String[] temp = filterTime.split(" - "); String[] temp = filterTime.split(" - ");
if (temp.length == 2) { if (temp.length == 2) {
triggerTimeStart = DateUtil.parseDateTime(temp[0]); triggerTimeStart = DateUtil.parseDateTime(temp[0]);
@ -114,9 +114,12 @@ public class JobLogController {
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsTotal", list_count);
maps.put("data", list); // 分页列表 // 过滤后的总记录数
maps.put("recordsFiltered", list_count);
// 分页列表
maps.put("data", list);
return maps; return maps;
} }
@ -141,9 +144,10 @@ public class JobLogController {
public ReturnT<LogResult> logDetailCat(long logId, int fromLineNum){ public ReturnT<LogResult> logDetailCat(long logId, int fromLineNum){
try { try {
// valid // valid
XxlJobLog jobLog = xxlJobLogDao.load(logId); // todo, need to improve performance // todo, need to improve performance
XxlJobLog jobLog = xxlJobLogDao.load(logId);
if (jobLog == null) { if (jobLog == null) {
return new ReturnT<LogResult>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_logid_unvalid")); return new ReturnT<>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_logid_unvalid"));
} }
// log cat // log cat
@ -191,7 +195,7 @@ public class JobLogController {
runResult = executorBiz.kill(new KillParam(jobInfo.getId())); runResult = executorBiz.kill(new KillParam(jobInfo.getId()));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
runResult = new ReturnT<String>(500, e.getMessage()); runResult = new ReturnT<>(500, e.getMessage());
} }
if (ReturnT.SUCCESS_CODE == runResult.getCode()) { if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
@ -199,9 +203,9 @@ public class JobLogController {
log.setHandleMsg( I18nUtil.getString("joblog_kill_log_byman")+":" + (runResult.getMsg()!=null?runResult.getMsg():"")); log.setHandleMsg( I18nUtil.getString("joblog_kill_log_byman")+":" + (runResult.getMsg()!=null?runResult.getMsg():""));
log.setHandleTime(new Date()); log.setHandleTime(new Date());
XxlJobCompleter.updateHandleInfoAndFinish(log); XxlJobCompleter.updateHandleInfoAndFinish(log);
return new ReturnT<String>(runResult.getMsg()); return new ReturnT<>(runResult.getMsg());
} else { } else {
return new ReturnT<String>(500, runResult.getMsg()); return new ReturnT<>(500, runResult.getMsg());
} }
} }
@ -215,34 +219,43 @@ public class JobLogController {
Date clearBeforeTime = null; Date clearBeforeTime = null;
int clearBeforeNum = 0; int clearBeforeNum = 0;
if (type == 1) { if (type == 1) {
clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据 // 清理一个月之前日志数据
clearBeforeTime = DateUtil.addMonths(new Date(), -1);
} else if (type == 2) { } else if (type == 2) {
clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据 // 清理三个月之前日志数据
clearBeforeTime = DateUtil.addMonths(new Date(), -3);
} else if (type == 3) { } else if (type == 3) {
clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据 // 清理六个月之前日志数据
clearBeforeTime = DateUtil.addMonths(new Date(), -6);
} else if (type == 4) { } else if (type == 4) {
clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据 // 清理一年之前日志数据
clearBeforeTime = DateUtil.addYears(new Date(), -1);
} else if (type == 5) { } else if (type == 5) {
clearBeforeNum = 1000; // 清理一千条以前日志数据 // 清理一千条以前日志数据
clearBeforeNum = 1000;
} else if (type == 6) { } else if (type == 6) {
clearBeforeNum = 10000; // 清理一万条以前日志数据 // 清理一万条以前日志数据
clearBeforeNum = 10000;
} else if (type == 7) { } else if (type == 7) {
clearBeforeNum = 30000; // 清理三万条以前日志数据 // 清理三万条以前日志数据
clearBeforeNum = 30000;
} else if (type == 8) { } else if (type == 8) {
clearBeforeNum = 100000; // 清理十万条以前日志数据 // 清理十万条以前日志数据
clearBeforeNum = 100000;
} else if (type == 9) { } else if (type == 9) {
clearBeforeNum = 0; // 清理所有日志数据 // 清理所有日志数据
clearBeforeNum = 0;
} else { } else {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid")); return new ReturnT<>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid"));
} }
List<Long> logIds = null; List<Long> logIds = null;
do { do {
logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000); logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000);
if (logIds!=null && logIds.size()>0) { if (logIds!=null && !logIds.isEmpty()) {
xxlJobLogDao.clearLog(logIds); xxlJobLogDao.clearLog(logIds);
} }
} while (logIds!=null && logIds.size()>0); } while (logIds!=null && !logIds.isEmpty());
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }

View File

@ -65,9 +65,12 @@ public class JobUserController {
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsTotal", list_count);
maps.put("data", list); // 分页列表 // 过滤后的总记录数
maps.put("recordsFiltered", list_count);
// 分页列表
maps.put("data", list);
return maps; return maps;
} }

View File

@ -31,7 +31,8 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) { if (!(handler instanceof HandlerMethod)) {
return true; // proceed with the next interceptor // proceed with the next interceptor
return true;
} }
// if need login // if need login
@ -54,10 +55,12 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
if (needAdminuser && loginUser.getRole()!=1) { if (needAdminuser && loginUser.getRole()!=1) {
throw new RuntimeException(I18nUtil.getString("system_permission_limit")); throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
} }
request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser); // set loginUser, with request // set loginUser, with request
request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser);
} }
return true; // proceed with the next interceptor // proceed with the next interceptor
return true;
} }
@ -70,8 +73,8 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
* @return * @return
*/ */
public static XxlJobUser getLoginUser(HttpServletRequest request){ public static XxlJobUser getLoginUser(HttpServletRequest request){
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); // get loginUser, with request // get loginUser, with request
return loginUser; return (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
} }
/** /**
@ -96,13 +99,13 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
*/ */
public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all){ public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all){
List<XxlJobGroup> jobGroupList = new ArrayList<>(); List<XxlJobGroup> jobGroupList = new ArrayList<>();
if (jobGroupList_all!=null && jobGroupList_all.size()>0) { if (jobGroupList_all!=null && !jobGroupList_all.isEmpty()) {
XxlJobUser loginUser = PermissionInterceptor.getLoginUser(request); XxlJobUser loginUser = PermissionInterceptor.getLoginUser(request);
if (loginUser.getRole() == 1) { if (loginUser.getRole() == 1) {
jobGroupList = jobGroupList_all; jobGroupList = jobGroupList_all;
} else { } else {
List<String> groupIdStrs = new ArrayList<>(); List<String> groupIdStrs = new ArrayList<>();
if (loginUser.getPermission()!=null && loginUser.getPermission().trim().length()>0) { if (loginUser.getPermission()!=null && !loginUser.getPermission().trim().isEmpty()) {
groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(",")); groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
} }
for (XxlJobGroup groupItem:jobGroupList_all) { for (XxlJobGroup groupItem:jobGroupList_all) {

View File

@ -118,7 +118,8 @@ public class XxlJobAdminConfig implements InitializingBean, DisposableBean {
public int getLogretentiondays() { public int getLogretentiondays() {
if (logretentiondays < 7) { if (logretentiondays < 7) {
return -1; // Limit greater than or equal to 7, otherwise close // Limit greater than or equal to 7, otherwise close
return -1;
} }
return logretentiondays; return logretentiondays;
} }

View File

@ -1425,9 +1425,9 @@ public final class CronExpression implements Serializable, Cloneable {
} }
} else if (nthdayOfWeek != 0) { } else if (nthdayOfWeek != 0) {
// are we looking for the Nth XXX day in the month? // are we looking for the Nth XXX day in the month? desired
int dow = daysOfWeek.first(); // desired int dow = daysOfWeek.first();
// d-o-w // current d-o-w // d-o-w current d-o-w
int cDow = cl.get(Calendar.DAY_OF_WEEK); int cDow = cl.get(Calendar.DAY_OF_WEEK);
int daysToAdd = 0; int daysToAdd = 0;
if (cDow < dow) { if (cDow < dow) {

View File

@ -13,12 +13,14 @@ public class XxlJobGroup {
private int id; private int id;
private String appname; private String appname;
private String title; private String title;
private int addressType; // 执行器地址类型0=自动注册、1=手动录入 // 执行器地址类型0=自动注册、1=手动录入
private String addressList; // 执行器地址列表,多地址逗号分隔(手动录入) private int addressType;
// 执行器地址列表,多地址逗号分隔(手动录入)
private String addressList;
private Date updateTime; private Date updateTime;
// registry list // registry list // 执行器地址列表(系统注册)
private List<String> registryList; // 执行器地址列表(系统注册) private List<String> registryList;
public List<String> getRegistryList() { public List<String> getRegistryList() {
if (addressList!=null && addressList.trim().length()>0) { if (addressList!=null && addressList.trim().length()>0) {
registryList = new ArrayList<String>(Arrays.asList(addressList.split(","))); registryList = new ArrayList<String>(Arrays.asList(addressList.split(",")));

View File

@ -8,39 +8,57 @@ import java.util.Date;
* @author xuxueli 2016-1-12 18:25:49 * @author xuxueli 2016-1-12 18:25:49
*/ */
public class XxlJobInfo { public class XxlJobInfo {
// 主键ID
private int id; // 主键ID private int id;
// 执行器主键ID
private int jobGroup; // 执行器主键ID private int jobGroup;
private String jobDesc; private String jobDesc;
private Date addTime; private Date addTime;
private Date updateTime; private Date updateTime;
// 负责人
private String author; // 负责人 private String author;
private String alarmEmail; // 报警邮件 // 报警邮件
private String alarmEmail;
private String scheduleType; // 调度类型 // 调度类型
private String scheduleConf; // 调度配置,值含义取决于调度类型 private String scheduleType;
private String misfireStrategy; // 调度过期策略 // 调度配置,值含义取决于调度类型
private String scheduleConf;
// 调度过期策略
private String misfireStrategy;
private String executorRouteStrategy; // 执行器路由策略 // 执行器路由策略
private String executorHandler; // 执行器任务Handler名称 private String executorRouteStrategy;
private String executorParam; // 执行器,任务参数 // 执行器任务Handler名称
private String executorBlockStrategy; // 阻塞处理策略 private String executorHandler;
private int executorTimeout; // 任务执行超时时间,单位秒 // 执行器,任务参数
private int executorFailRetryCount; // 失败重试次数 private String executorParam;
// 阻塞处理策略
private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private String executorBlockStrategy;
private String glueSource; // GLUE源代码 // 任务执行超时时间,单位秒
private String glueRemark; // GLUE备注 private int executorTimeout;
private Date glueUpdatetime; // GLUE更新时间 // 失败重试次数
private int executorFailRetryCount;
private String childJobId; // 子任务ID多个逗号分隔 // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum
private String glueType;
// GLUE源代码
private String glueSource;
// GLUE备注
private String glueRemark;
// GLUE更新时间
private Date glueUpdatetime;
private int triggerStatus; // 调度状态0-停止1-运行 // 子任务ID多个逗号分隔
private long triggerLastTime; // 上次调度时间 private String childJobId;
private long triggerNextTime; // 下次调度时间
// 调度状态0-停止1-运行
private int triggerStatus;
// 上次调度时间
private long triggerLastTime;
// 下次调度时间
private long triggerNextTime;
public int getId() { public int getId() {

View File

@ -9,8 +9,10 @@ import java.util.Date;
public class XxlJobLogGlue { public class XxlJobLogGlue {
private int id; private int id;
private int jobId; // 任务主键ID // 任务主键ID
private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private int jobId;
// GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum
private String glueType;
private String glueSource; private String glueSource;
private String glueRemark; private String glueRemark;
private Date addTime; private Date addTime;

View File

@ -8,10 +8,14 @@ import org.springframework.util.StringUtils;
public class XxlJobUser { public class XxlJobUser {
private int id; private int id;
private String username; // 账号 // 账号
private String password; // 密码 private String username;
private int role; // 角色0-普通用户、1-管理员 // 密码
private String permission; // 权限执行器ID列表多个逗号分割 private String password;
// 角色0-普通用户、1-管理员
private int role;
// 权限执行器ID列表多个逗号分割
private String permission;
public int getId() { public int getId() {
return id; return id;

View File

@ -40,7 +40,8 @@ public class ExecutorRouteLFU extends ExecutorRouter {
// put new // put new
for (String address: addressList) { for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) { if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次缓解首次压力 // 初始化时主动Random一次缓解首次压力
lfuItemMap.put(address, new Random().nextInt(addressList.size()));
} }
} }
// remove old // remove old

View File

@ -27,7 +27,8 @@ public class JobScheduleHelper {
return instance; return instance;
} }
public static final long PRE_READ_MS = 5000; // pre read // pre read
public static final long PRE_READ_MS = 5000;
private Thread scheduleThread; private Thread scheduleThread;
private Thread ringThread; private Thread ringThread;
@ -311,7 +312,8 @@ public class JobScheduleHelper {
// 1、stop schedule // 1、stop schedule
scheduleThreadToStop = true; scheduleThreadToStop = true;
try { try {
TimeUnit.SECONDS.sleep(1); // wait // wait
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
@ -371,7 +373,8 @@ public class JobScheduleHelper {
if (ScheduleTypeEnum.CRON == scheduleTypeEnum) { if (ScheduleTypeEnum.CRON == scheduleTypeEnum) {
Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime); Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime);
return nextValidTime; return nextValidTime;
} else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) { /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/
} else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum ) {
return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf())*1000 ); return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf())*1000 );
} }
return null; return null;

View File

@ -62,8 +62,9 @@ public class JobTriggerPoolHelper {
// job timeout count // job timeout count
private volatile long minTim = System.currentTimeMillis()/60000; // ms > min // ms > min
private volatile ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>(); private final ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>();
private volatile long minTim = System.currentTimeMillis()/60000;
/** /**
@ -77,14 +78,15 @@ public class JobTriggerPoolHelper {
final String addressList) { final String addressList) {
// choose thread pool // choose thread pool
ThreadPoolExecutor triggerPool_ = fastTriggerPool; ThreadPoolExecutor triggerPool = fastTriggerPool;
AtomicInteger jobTimeoutCount = jobTimeoutCountMap.get(jobId); AtomicInteger jobTimeoutCount = jobTimeoutCountMap.get(jobId);
if (jobTimeoutCount!=null && jobTimeoutCount.get() > 10) { // job-timeout 10 times in 1 min // job-timeout 10 times in 1 min
triggerPool_ = slowTriggerPool; if (jobTimeoutCount!=null && jobTimeoutCount.get() > 10) {
triggerPool = slowTriggerPool;
} }
// trigger // trigger
triggerPool_.execute(new Runnable() { triggerPool.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -98,9 +100,9 @@ public class JobTriggerPoolHelper {
} finally { } finally {
// check timeout-count-map // check timeout-count-map
long minTim_now = System.currentTimeMillis()/60000; long minTimNow = System.currentTimeMillis()/60000;
if (minTim != minTim_now) { if (minTim != minTimNow) {
minTim = minTim_now; minTim = minTimNow;
jobTimeoutCountMap.clear(); jobTimeoutCountMap.clear();
} }

View File

@ -111,8 +111,10 @@ public class XxlJobTrigger {
private static void processTrigger(XxlJobGroup group, XxlJobInfo jobInfo, int finalFailRetryCount, TriggerTypeEnum triggerType, int index, int total){ private static void processTrigger(XxlJobGroup group, XxlJobInfo jobInfo, int finalFailRetryCount, TriggerTypeEnum triggerType, int index, int total){
// param // param
ExecutorBlockStrategyEnum blockStrategy = ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), ExecutorBlockStrategyEnum.SERIAL_EXECUTION); // block strategy // block strategy
ExecutorRouteStrategyEnum executorRouteStrategyEnum = ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null); // route strategy ExecutorBlockStrategyEnum blockStrategy = ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), ExecutorBlockStrategyEnum.SERIAL_EXECUTION);
// route strategy
ExecutorRouteStrategyEnum executorRouteStrategyEnum = ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null);
String shardingParam = (ExecutorRouteStrategyEnum.SHARDING_BROADCAST==executorRouteStrategyEnum)?String.valueOf(index).concat("/").concat(String.valueOf(total)):null; String shardingParam = (ExecutorRouteStrategyEnum.SHARDING_BROADCAST==executorRouteStrategyEnum)?String.valueOf(index).concat("/").concat(String.valueOf(total)):null;
// 1、save log-id // 1、save log-id

View File

@ -54,9 +54,12 @@ public class XxlJobServiceImpl implements XxlJobService {
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsTotal", list_count);
maps.put("data", list); // 分页列表 // 过滤后的总记录数
maps.put("recordsFiltered", list_count);
// 分页列表
maps.put("data", list);
return maps; return maps;
} }
@ -84,12 +87,13 @@ public class XxlJobServiceImpl implements XxlJobService {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) { if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid")); return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid"));
} }
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE/* || scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) { /* || scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE) {
if (jobInfo.getScheduleConf() == null) { if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")) );
} }
try { try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf()); int fixSecond = Integer.parseInt(jobInfo.getScheduleConf());
if (fixSecond < 1) { if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
} }
@ -192,12 +196,13 @@ public class XxlJobServiceImpl implements XxlJobService {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) { if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid") ); return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid") );
} }
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE /*|| scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) { /*|| scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE) {
if (jobInfo.getScheduleConf() == null) { if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
} }
try { try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf()); int fixSecond = Integer.parseInt(jobInfo.getScheduleConf());
if (fixSecond < 1) { if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
} }

View File

@ -68,7 +68,8 @@ public class XxlJobContext {
this.shardIndex = shardIndex; this.shardIndex = shardIndex;
this.shardTotal = shardTotal; this.shardTotal = shardTotal;
this.handleCode = HANDLE_CODE_SUCCESS; // default success // default success
this.handleCode = HANDLE_CODE_SUCCESS;
} }
public long getJobId() { public long getJobId() {
@ -109,7 +110,8 @@ public class XxlJobContext {
// ---------------------- tool ---------------------- // ---------------------- tool ----------------------
private static InheritableThreadLocal<XxlJobContext> contextHolder = new InheritableThreadLocal<XxlJobContext>(); // support for child thread of job handler) // support for child thread of job handler)
private static InheritableThreadLocal<XxlJobContext> contextHolder = new InheritableThreadLocal<XxlJobContext>();
public static void setXxlJobContext(XxlJobContext xxlJobContext){ public static void setXxlJobContext(XxlJobContext xxlJobContext){
contextHolder.set(xxlJobContext); contextHolder.set(xxlJobContext);

View File

@ -144,16 +144,17 @@ public class XxlJobExecutor {
// fill ip port // fill ip port
port = port>0?port: NetUtil.findAvailablePort(9999); port = port>0?port: NetUtil.findAvailablePort(9999);
ip = (ip!=null&&ip.trim().length()>0)?ip: IpUtil.getIp(); ip = (ip!=null&& !ip.trim().isEmpty())?ip: IpUtil.getIp();
// generate address // generate address
if (address==null || address.trim().length()==0) { if (address==null || address.trim().isEmpty()) {
String ip_port_address = IpUtil.getIpPort(ip, port); // registry-addressdefault use address to registry , otherwise use ip:port if address is null // registry-addressdefault use address to registry , otherwise use ip:port if address is null
address = "http://{ip_port}/".replace("{ip_port}", ip_port_address); String ipPortAddress = IpUtil.getIpPort(ip, port);
address = "http://{ip_port}/".replace("{ip_port}", ipPortAddress);
} }
// accessToken // accessToken
if (accessToken==null || accessToken.trim().length()==0) { if (accessToken==null || accessToken.trim().isEmpty()) {
logger.warn(">>>>>>>>>>> xxl-job accessToken is empty. To ensure system security, please set the accessToken."); logger.warn(">>>>>>>>>>> xxl-job accessToken is empty. To ensure system security, please set the accessToken.");
} }
@ -245,7 +246,8 @@ public class XxlJobExecutor {
newJobThread.start(); newJobThread.start();
logger.info(">>>>>>>>>>> xxl-job regist JobThread success, jobId:{}, handler:{}", new Object[]{jobId, handler}); logger.info(">>>>>>>>>>> xxl-job regist JobThread success, jobId:{}, handler:{}", new Object[]{jobId, handler});
JobThread oldJobThread = jobThreadRepository.put(jobId, newJobThread); // putIfAbsent | oh my god, map's put method return the old value!!! // putIfAbsent | oh my god, map's put method return the old value!!!
JobThread oldJobThread = jobThreadRepository.put(jobId, newJobThread);
if (oldJobThread != null) { if (oldJobThread != null) {
oldJobThread.toStop(removeOldReason); oldJobThread.toStop(removeOldReason);
oldJobThread.interrupt(); oldJobThread.interrupt();

View File

@ -96,7 +96,8 @@ public class XxlJobSpringExecutor extends XxlJobExecutor implements ApplicationC
} }
// filter method // filter method
Map<Method, XxlJob> annotatedMethods = null; // referred to org.springframework.context.event.EventListenerMethodProcessor.processBean // referred to org.springframework.context.event.EventListenerMethodProcessor.processBean
Map<Method, XxlJob> annotatedMethods = null;
try { try {
annotatedMethods = MethodIntrospector.selectMethods(bean.getClass(), annotatedMethods = MethodIntrospector.selectMethods(bean.getClass(),
new MethodIntrospector.MetadataLookup<XxlJob>() { new MethodIntrospector.MetadataLookup<XxlJob>() {

View File

@ -26,7 +26,8 @@ public class MethodJobHandler extends IJobHandler {
public void execute() throws Exception { public void execute() throws Exception {
Class<?>[] paramTypes = method.getParameterTypes(); Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) { if (paramTypes.length > 0) {
method.invoke(target, new Object[paramTypes.length]); // method-param can not be primitive-types // method-param can not be primitive-types
method.invoke(target, new Object[paramTypes.length]);
} else { } else {
method.invoke(target); method.invoke(target);
} }

View File

@ -66,7 +66,8 @@ public class XxlJobFileAppender {
public static String makeLogFileName(Date triggerDate, long logId) { public static String makeLogFileName(Date triggerDate, long logId) {
// filePath/yyyy-MM-dd // filePath/yyyy-MM-dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // avoid concurrent problem, can not be static // avoid concurrent problem, can not be static
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
File logFilePath = new File(getLogPath(), sdf.format(triggerDate)); File logFilePath = new File(getLogPath(), sdf.format(triggerDate));
if (!logFilePath.exists()) { if (!logFilePath.exists()) {
logFilePath.mkdir(); logFilePath.mkdir();
@ -157,7 +158,8 @@ public class XxlJobFileAppender {
String line = null; String line = null;
while ((line = reader.readLine())!=null) { while ((line = reader.readLine())!=null) {
toLineNum = reader.getLineNumber(); // [from, to], start as 1 // [from, to], start as 1
toLineNum = reader.getLineNumber();
if (toLineNum >= fromLineNum) { if (toLineNum >= fromLineNum) {
logContentBuffer.append(line).append("\n"); logContentBuffer.append(line).append("\n");
} }

View File

@ -27,16 +27,18 @@ import java.util.concurrent.*;
public class JobThread extends Thread{ public class JobThread extends Thread{
private static Logger logger = LoggerFactory.getLogger(JobThread.class); private static Logger logger = LoggerFactory.getLogger(JobThread.class);
private int jobId; private final int jobId;
private IJobHandler handler; private final IJobHandler handler;
private LinkedBlockingQueue<TriggerParam> triggerQueue; private final LinkedBlockingQueue<TriggerParam> triggerQueue;
private Set<Long> triggerLogIdSet; // avoid repeat trigger for the same TRIGGER_LOG_ID // avoid repeat trigger for the same TRIGGER_LOG_ID
private final Set<Long> triggerLogIdSet;
private volatile boolean toStop = false; private volatile boolean toStop = false;
private String stopReason; private String stopReason;
// if running job
private boolean running = false; // if running job private boolean running = false;
private int idleTimes = 0; // idel times // idel times
private int idleTimes = 0;
public JobThread(int jobId, IJobHandler handler) { public JobThread(int jobId, IJobHandler handler) {
@ -184,7 +186,8 @@ public class JobThread extends Thread{
} else { } else {
if (idleTimes > 30) { if (idleTimes > 30) {
if(triggerQueue.size() == 0) { // avoid concurrent trigger causes jobId-lost // avoid concurrent trigger causes jobId-lost
if(triggerQueue.size() == 0) {
XxlJobExecutor.removeJobThread(jobId, "excutor idel times over limit."); XxlJobExecutor.removeJobThread(jobId, "excutor idel times over limit.");
} }
} }

View File

@ -135,7 +135,8 @@ public class TriggerCallbackThread {
public void toStop(){ public void toStop(){
toStop = true; toStop = true;
// stop callback, interrupt and wait // stop callback, interrupt and wait
if (triggerCallbackThread != null) { // support empty admin address // support empty admin address
if (triggerCallbackThread != null) {
triggerCallbackThread.interrupt(); triggerCallbackThread.interrupt();
try { try {
triggerCallbackThread.join(); triggerCallbackThread.join();

View File

@ -101,7 +101,8 @@ public class ScriptUtil {
errThread.start(); errThread.start();
// process-wait // process-wait
int exitValue = process.waitFor(); // exit code: 0=success, 1=error // exit code: 0=success, 1=error
int exitValue = process.waitFor();
// log-thread join // log-thread join
inputThread.join(); inputThread.join();