Quartz+Mybatis+SpringMvc+SpringBoot整合(二)

发布于 2019-11-10  177 次阅读


上文Quartz+Mybatis+SpringMvc+SpringBoot整合(一)主要讲了基本的配置,下面讲mapper,.service,以及controller的定义.

新建SchedulerMapper

public interface SchedulerMapper {
    /**
     * 获取当前所有任务列表
     */
    List<SchedulerEntity> getSchedulerList();

    /**
     * 获取任务详情
     */
    SchedulerEntity detail(String jobName, String jobGroup);
}

新建SchedulerService接口

public interface SchedulerService {
    /**
     * @param queryBase
     * @描述: 获取分页数据
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:25 2019/11/10
     */
    Result<DataTableModel> getPageData(QueryBase queryBase);
    /**
     * @param entity
     * @描述: 删除任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:26 2019/11/10
     */
    Result<String> delete(SchedulerEntity entity);
    /**
     * @param entity
     * @描述: 编辑任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 10:01 2019/11/10
     */
    Result<String> edit(SchedulerEntity entity) throws SystemException;
    /**
     * @param entity
     * @描述: 获取任务详情
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:27 2019/11/10
     */
    Result<SchedulerEntity> detail(SchedulerEntity entity);
    /**
     * @param entity
     * @描述: 添加任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:27 2019/11/10
     */
    Result<String> add(SchedulerEntity entity) throws SystemException;
    /**
     * @param entity
     * @param scheduleBuilder
     * @描述: 设置simple类型任务的builder属性
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:12 2019/11/10
     */
    Result<String> setSimpleScheduleBuilder(SchedulerEntity entity, SimpleScheduleBuilder scheduleBuilder);
    /**
     * @param entity
     * @描述: 恢复任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:14 2019/11/10
     */
    Result<String> resume(SchedulerEntity entity) throws SchedulerException;
    /**
     * @param entity
     * @描述: 暂停任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:41 2019/11/10
     */
    Result<String> pause(SchedulerEntity entity) throws SchedulerException;
    /**
     * @param
     * @描述: 停止所有任务,注意:停止后不可重新启动
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:14 2019/11/10
     */
    Result<String> shutdownJob() throws SchedulerException;
    /**
     * @param
     * @描述: 开始任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:15 2019/11/10
     */
    Result<String> startJob() throws SchedulerException;
    /**
     * @param
     * @描述: 临时停止任务(可重新开始)
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:15 2019/11/10
     */
    Result<String> standbyJob() throws SchedulerException;
}

新建SchedulerServiceImpl实现类

@Service("SchedulerService")
public class SchedulerServiceImpl implements SchedulerService {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    SchedulerMapper schedulerMapper;

    /**
     * @param queryBase
     * @描述: 获取分页数据
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:25 2019/11/10
     */
    @Override
    public Result<DataTableModel> getPageData(QueryBase queryBase) {

        Result<DataTableModel> result = new Result<>();
        DataTableModel data = new DataTableModel();
        PageHelper.startPage(queryBase.getPageIndex(), queryBase.getPageSize());
        var scheduler = new PageInfo<SchedulerEntity>(schedulerMapper.getSchedulerList());
        data.setData(scheduler.getList());
        data.setRecordsTotal(scheduler.getTotal());
        result.setData(data);
        result.success();
        return result;
    }

    /**
     * @param entity
     * @描述: 删除任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:26 2019/11/10
     */
    @Override
    public Result<String> delete(SchedulerEntity entity) {

        var result = new Result<String>();
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(entity.getJobName(), entity.getJobGroup()));
            scheduler.unscheduleJob(TriggerKey.triggerKey(entity.getJobName(), entity.getJobGroup()));
            scheduler.deleteJob(JobKey.jobKey(entity.getJobName(), entity.getJobGroup()));
            result.success();
        } catch (SchedulerException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * @param entity
     * @描述: 添加任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:27 2019/11/10
     */
    @Override
    public Result<String> add(SchedulerEntity entity) throws SystemException {

        var result = new Result<String>();
        try {
            // 启动调度器
            scheduler.start();
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ObjectHelper.<BaseJob>getInstance(entity.getJobClassName()).getClass())
                    .withIdentity(entity.getJobName(), entity.getJobGroup()).withDescription(entity.getDescription()).build();
            Trigger trigger = null;
            switch (ScheduleTriggerType.valueOf(entity.getTriggerType())) {
                case CRON:
                    CronScheduleBuilder cronBuilder = CronScheduleBuilder.cronSchedule(entity.getCronExpression());
                    trigger = TriggerBuilder.newTrigger().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(cronBuilder).build();
                    break;
                case SIMPLE:
                    SimpleScheduleBuilder simpleBuilder = SimpleScheduleBuilder.simpleSchedule();
                    var setResult = this.setSimpleScheduleBuilder(entity, simpleBuilder);
                    trigger = TriggerBuilder.newTrigger().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(simpleBuilder).build();
                    break;
                case DAILY_I:
                    DailyTimeIntervalScheduleBuilder dailyTimeBuilder = DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule();
                    dailyTimeBuilder.withInterval(entity.getTimeInterval(), DateBuilder.IntervalUnit.valueOf(entity.getIntervalUnit()));
                    trigger = TriggerBuilder.newTrigger().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(dailyTimeBuilder).build();
                    break;
                case CAL_INT:
                    CalendarIntervalScheduleBuilder calendarBuilder = CalendarIntervalScheduleBuilder.calendarIntervalSchedule();
                    calendarBuilder.withInterval(entity.getTimeInterval(), DateBuilder.IntervalUnit.valueOf(entity.getIntervalUnit()));
                    trigger = TriggerBuilder.newTrigger().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(calendarBuilder).build();
                    break;
                default:
                    result.error(ErrorEnum.ERR_1, "错误的触发器类型:" + entity.getTriggerType());
                    return result;
            }
            scheduler.scheduleJob(jobDetail, trigger);
            result.success();
        } catch (Exception e) {
            throw new SystemException(ErrorEnum.ERR_1, e.getMessage());
        }
        return result;
    }

    /**
     * @param entity
     * @描述: 获取任务详情
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:27 2019/11/10
     */
    @Override
    public Result<SchedulerEntity> detail(SchedulerEntity entity) {
        var result = new Result<SchedulerEntity>();
        result.setData(schedulerMapper.detail(entity.getJobName(), entity.getJobGroup()));
        result.success();
        return result;
    }

    /**
     * @param entity
     * @描述: 编辑任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 10:01 2019/11/10
     */
    @Override
    public Result<String> edit(SchedulerEntity entity) throws SystemException {
        var result = new Result<String>();
        try {
            //找到该Trigger
            TriggerKey triggerKey = TriggerKey.triggerKey(entity.getJobName(), entity.getJobGroup());
            Trigger trigger = null;
            switch (ScheduleTriggerType.valueOf(entity.getTriggerType())) {
                case CRON:
                    CronScheduleBuilder cronBuilder = CronScheduleBuilder.cronSchedule(entity.getCronExpression());
                    var crontrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
                    trigger = crontrigger.getTriggerBuilder().withPriority(entity.getPriority()).withIdentity(triggerKey)
                            .withSchedule(cronBuilder).build();
                    break;
                case SIMPLE:
                    SimpleScheduleBuilder simpleBuilder = SimpleScheduleBuilder.simpleSchedule();
                    var setResult = this.setSimpleScheduleBuilder(entity, simpleBuilder);
                    if (!setResult.isSuccess()) {
                        return result;
                    }
                    var simpleTrigger = (SimpleTrigger) scheduler.getTrigger(triggerKey);
                    trigger = simpleTrigger.getTriggerBuilder().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(simpleBuilder).build();
                case DAILY_I:
                    DailyTimeIntervalScheduleBuilder dailyTimeBuilder = DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule();
                    dailyTimeBuilder.withInterval(entity.getTimeInterval(), DateBuilder.IntervalUnit.valueOf(entity.getIntervalUnit()));
                    var dailyTimeTrigger = (DailyTimeIntervalTrigger) scheduler.getTrigger(triggerKey);
                    trigger = dailyTimeTrigger.getTriggerBuilder().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(dailyTimeBuilder).build();
                    break;
                case CAL_INT:
                    CalendarIntervalScheduleBuilder calendarBuilder = CalendarIntervalScheduleBuilder.calendarIntervalSchedule();
                    calendarBuilder.withInterval(entity.getTimeInterval(), DateBuilder.IntervalUnit.valueOf(entity.getIntervalUnit()));
                    var calendarTrigger = (CalendarIntervalTrigger) scheduler.getTrigger(triggerKey);
                    trigger = calendarTrigger.getTriggerBuilder().withPriority(entity.getPriority()).withIdentity(entity.getJobName(), entity.getJobGroup())
                            .withSchedule(calendarBuilder).build();
                    break;
                default:
                    result.error(ErrorEnum.ERR_1, "错误的触发器类型:" + entity.getTriggerType());
                    return result;
            }
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
            result.success();
        } catch (Exception e) {
            throw new SystemException(ErrorEnum.ERR_1, e.getMessage());
        }
        return result;
    }

    /**
     * @param entity
     * @param scheduleBuilder
     * @描述: 设置simple类型任务的builder属性
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:12 2019/11/10
     */
    @Override
    public Result<String> setSimpleScheduleBuilder(SchedulerEntity entity, SimpleScheduleBuilder scheduleBuilder) {

        var result = new Result<String>();
        //次数不限
        if ("forever".equals(entity.getRepeatCount())) {
            scheduleBuilder.repeatForever();
        } else {
            scheduleBuilder.withRepeatCount(entity.getRepeatCount());
        }
        //MILLISECOND,SECOND,MINUTE,HOUR,
        switch (DateBuilder.IntervalUnit.valueOf(entity.getIntervalUnit())) {
            case MILLISECOND:
                scheduleBuilder.withIntervalInMilliseconds(entity.getRepeatInterval());
                break;
            case SECOND:
                scheduleBuilder.withIntervalInSeconds(new Long(entity.getRepeatInterval()).intValue());
                break;
            case MINUTE:
                scheduleBuilder.withIntervalInMinutes(new Long(entity.getRepeatInterval()).intValue());
                break;
            case HOUR:
                scheduleBuilder.withIntervalInHours(new Long(entity.getRepeatInterval()).intValue());
                break;
            default:
                result.error(ErrorEnum.ERR_1, "错误的时间单位:" + entity.getIntervalUnit());
                return result;
        }
        result.success();
        return result;
    }


    /**
     * @param entity
     * @描述: 暂停任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 9:41 2019/11/10
     */
    @Override
    public Result<String> pause(SchedulerEntity entity) throws SchedulerException {

        var result = new Result<String>();
        try {
            scheduler.pauseJob(JobKey.jobKey(entity.getJobName(), entity.getJobGroup()));
            result.success();
        } catch (SchedulerException e) {
            throw new SchedulerException(e);
        }
        return result;
    }

    /**
     * @param entity
     * @描述: 恢复任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:14 2019/11/10
     */
    @Override
    public Result<String> resume(SchedulerEntity entity) throws SchedulerException {

        var result = new Result<String>();
        try {
            scheduler.resumeJob(JobKey.jobKey(entity.getJobName(), entity.getJobGroup()));
            result.success();
        } catch (SchedulerException e) {
            throw new SchedulerException(e);
        }
        return result;
    }

    /**
     * @param
     * @描述: 停止所有任务,注意:停止后不可重新启动
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:14 2019/11/10
     */
    @Override
    public Result<String> shutdownJob() throws SchedulerException {

        var result = new Result<String>();
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
                result.success();
            }
        } catch (SchedulerException e) {
            throw new SchedulerException(e);
        }
        return result;
    }

    /**
     * @param
     * @描述: 启动任务
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:15 2019/11/10
     */
    @Override
    public Result<String> startJob() throws SchedulerException {

        var result = new Result<String>();
        try {
            scheduler.start();
            result.success();
        } catch (SchedulerException e) {
            throw new SchedulerException(e);
        }
        return result;
    }

    /**
     * @param
     * @描述: 临时停止任务(可重新开始)
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:15 2019/11/10
     */
    @Override
    public Result<String> standbyJob() throws SchedulerException {

        var result = new Result<String>();
        try {
            scheduler.standby();
            result.success();
        } catch (SchedulerException e) {
            throw new SchedulerException(e);
        }
        return result;
    }
}

新建控制器SchedulerController

@RestController
@RequestMapping("/admin/scheduler")
public class SchedulerController {
    @Autowired
    private SchedulerService schedulerService;

    @GetMapping("/getFields")
    @ResponseBody
    public String getFields(HttpServletRequest request) {
        var result = new Result<SchedulerEntity>();
        result.setData(new SchedulerEntity());
        return result.successJson();
    }

    @GetMapping("/getTriggerType")
    @ResponseBody
    public String getTriggerType(SchedulerEntity entity, HttpServletRequest request) throws SystemException {
        var result = new Result<Object>();
        result.setData(EnumHelper.getEnumNameAndValue(ScheduleTriggerType.class));
        return result.successJson();
    }

    @GetMapping("/detail")
    @ResponseBody
    public String detail(SchedulerEntity entity, HttpServletRequest request) {
        return schedulerService.detail(entity).toJson();
    }

    @PostMapping(value = "/add")
    public String add(@RequestBody SchedulerEntity entity, HttpServletRequest request) throws Exception {
        return schedulerService.add(entity).toJson();
    }

    @PostMapping(value = "/pause")
    public String pause(@RequestBody SchedulerEntity entity, HttpServletRequest request) throws SchedulerException {
        return schedulerService.pause(entity).toJson();
    }

    @PostMapping(value = "/resume")
    public String resume(@RequestBody SchedulerEntity entity, HttpServletRequest request) throws SchedulerException {
        return schedulerService.resume(entity).toJson();
    }

    @PostMapping(value = "/edit")
    public String edit(@RequestBody SchedulerEntity entity, HttpServletRequest request) throws Exception {
        return schedulerService.edit(entity).toJson();
    }

    @PostMapping(value = "/shutdownJob")
    public String shutdownAll(HttpServletRequest request) throws SchedulerException {
        return schedulerService.shutdownJob().toJson();
    }

    @PostMapping(value = "/standbyJob")
    public String standbyJob(HttpServletRequest request) throws SchedulerException {
        return schedulerService.standbyJob().toJson();
    }

    @PostMapping(value = "/startJob")
    public String startJob(HttpServletRequest request) throws SchedulerException {
        return schedulerService.startJob().toJson();
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody SchedulerEntity entity, HttpServletRequest request) {
        return schedulerService.delete(entity).toJson();
    }

    @GetMapping(value = "/getPageData")
    public String getPageData(QueryBase queryBase, HttpServletRequest request) {
        return schedulerService.getPageData(queryBase).toJson();
    }

    @GetMapping(value = "/getJobList")
    public String getJobList(QueryBase queryBase, HttpServletRequest request) {
        var result = new Result<List<JobModel>>();
        result.setData(ScheduleUtil.getJobList());
        return result.successJson();
    }
}

补充:我用到的Result类以及EnumHelper、ScheduleTriggerType枚举类

@Data
public class Result<T> {
    private String msg;
    private T data;
    private String code;

    public Result() {
    }

    private static ValueFilter filter = new ValueFilter() {
        @Override
        public Object process(Object obj, String s, Object v) {
            if (v == null) {
                return "";
            }
            return v;
        }
    };

    public String toJson() {
        return JSON.toJSONString(this, filter,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNonStringKeyAsString,
                SerializerFeature.WriteNonStringValueAsString,
                SerializerFeature.BrowserCompatible
        );
    }
    
    public String successJson() {
        //默认成功
        this.code = "0";
        this.msg = "操作成功";
        return this.toJson();

    }

    public String successJson(String msg) {
        //默认成功
        this.code = "0";
        this.msg = msg;
        return this.toJson();

    }

    public String errorJson(ErrorEnum errorEnum) {
        this.msg = errorEnum.getErrorMsg();
        this.code = errorEnum.getErrorCode();
        return this.toJson();
    }

    public String errorJson(ErrorEnum errorEnum, String msg) {
        this.msg = msg == null || msg.isEmpty() ? errorEnum.getErrorMsg() : errorEnum.getErrorMsg() + ":" + msg;
        this.code = errorEnum.getErrorCode();
        return this.toJson();
    }

    public void success() {
        //默认成功
        this.code = "0";
        this.msg = "操作成功";

    }

    public void success(String msg) {
        //默认成功
        this.code = "0";
        this.msg = msg;
    }

    public boolean isSuccess() {
        return "0".equals(this.code);
    }

    public void error(ErrorEnum errorEnum) {
        this.msg = errorEnum.getErrorMsg();
        this.code = errorEnum.getErrorCode();

    }

    public void error(ErrorEnum errorEnum, String msg) {
        this.msg = errorEnum.getErrorMsg() + ":" + msg;
        this.code = errorEnum.getErrorCode();

    }
}

public class EnumHelper {
    /**
     * @param em      枚举类
     * @param getName 是否获取name属性
     * @描述: 获取枚举类的name或value属性
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:38 2019/11/10
     */
    public static List<String> getEnumNameOrValue(Class<?> em, boolean getName) throws SystemException {
        var result = new ArrayList<String>();
        try {
            Method toName = em.getMethod("getName");
            Method toValue = em.getMethod("getValue");
            Object[] objs = em.getEnumConstants();
            for (var o : objs) {
                if (getName) {
                    result.add(toName.invoke(o).toString());
                } else {
                    result.add(toValue.invoke(o).toString());
                }
            }
        } catch (Exception e) {
            throw new SystemException(ErrorEnum.ERR_1, MessageFormat.format("获取枚举类{0}属性出错", em.getName()));
        }
        return result;
    }

    /**
     * @param em 枚举类
     * @描述: 获取枚举类的name和value属性
     * @返回值:
     * @创建人: LoneKing
     * @创建时间: 20:38 2019/11/10
     */
    public static List<SelectListItem> getEnumNameAndValue(Class<?> em) throws SystemException {

        var result = new ArrayList<SelectListItem>();
        try {
            Method toName = em.getMethod("getName");
            Method toValue = em.getMethod("getValue");
            Object[] objs = em.getEnumConstants();
            for (var o : objs) {
                var item = new SelectListItem();
                item.setName(toName.invoke(o).toString());
                item.setValue(toValue.invoke(o).toString());
                result.add(item);
            }
        } catch (Exception e) {
            throw new SystemException(ErrorEnum.ERR_1, MessageFormat.format("获取枚举类{0}属性出错", em.getName()));
        }
        return result;
    }
}
/**
 * Quartz触发器类型
 */
public enum ScheduleTriggerType {
    /**
     * simple简单类型任务
     */
    SIMPLE("SIMPLE", "SIMPLE"),
    /**
     * cron类型任务
     */
    CRON("CRON", "CRON"),
    /**
     * calendar类型任务
     */
    CAL_INT("CAL_INT", "CAL_INT"),
    /**
     * blob类型任务
     */
    BLOB("BLOB", "BLOB"),
    /**
     * dailiTime类型任务
     */
    DAILY_I("DAILY_I", "DAILY_I");

    private final String value;
    private final String name;

    ScheduleTriggerType(String value, String name) {
        this.value = value;
        this.name = name;
    }

    public String getValue() {
        return this.value;
    }

    public String getName() {
        return this.name;
    }

    public static String getNameByValue(String value) {
        for (ScheduleTriggerType e : ScheduleTriggerType.values()
        ) {
            if (value.equals(e.getValue())) {
                return e.getName();
            }
        }
        return "";
    }
}

接下来第三部分,也就是最后一部分放vue前端控制那一部分,点击前往Quartz+Mybatis+SpringMvc+SpringBoot整合(三)


LoneKing