大熊猫分布式组件开发系列教程(三)

2023-11-01 06:50

本文主要是介绍大熊猫分布式组件开发系列教程(三),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天我们来看看springboot定时任务如何做成分布式组件来供项目集成依赖使用,接下来就跟着大熊猫一起做crontask分布式组件开发。

首先我们先创建一个crontask模块

其实这个定时任务组件最主要的操作就是定时任务记录,以及定时任务日志这两张表

接着就是一些工厂类的封装,监听类的实现

编写JpJob实现Job的excute方法,以及编写执行之前的方法,执行后的方法。

package com.panda.common.crontask.web.schedule;
import com.panda.common.crontask.common.DateUtil;
import com.panda.common.crontask.service.api.QuartzConfigService;
import com.panda.common.crontask.service.api.QuartzLogService;
import com.panda.common.crontask.service.api.dto.QuartzConfigDto;
import com.panda.common.crontask.service.api.dto.QuartzLogDto;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
public abstract class JpJob implements Job, Serializable {private static Logger logger = LoggerFactory.getLogger(JpJob.class);@Autowiredprivate QuartzLogService quartzLogService;@Autowiredprivate QuartzConfigService quartzConfigService;//任务开始时间private ThreadLocal<LocalDateTime> beforTime = new ThreadLocal<>();//日志Idprivate ThreadLocal<String> logId = new ThreadLocal<>();public abstract void runJob();public void beforeRun(){String clazz = this.getClass().getName();QuartzLogDto quartzLogDto = new QuartzLogDto();quartzLogDto.setClazz(clazz);QuartzConfigDto quartzConfigDto = quartzConfigService.findByClazz(clazz);if(quartzConfigDto != null){quartzLogDto.setQuartzId(quartzConfigDto.getId());quartzLogDto.setName(quartzConfigDto.getName());}quartzLogDto = quartzLogService.add(quartzLogDto);beforTime.set(LocalDateTime.now());logId.set(quartzLogDto.getId());}public void error(Exception e){QuartzLogDto quartzLogDto = quartzLogService.get(logId.get());Duration between = Duration.between(beforTime.get(), LocalDateTime.now());quartzLogDto.setSpendTime(between.toMillis());if(e != null && e.getMessage() != null)quartzLogDto.setExceptionMessage(e.getMessage().length() > 500 ? e.getMessage().substring(0, 499) : e.getMessage());quartzLogDto.setResult(0);quartzLogService.update(logId.get(), quartzLogDto);}public void afterRun(){QuartzLogDto quartzLogDto = quartzLogService.get(logId.get());Duration between = Duration.between(beforTime.get(), LocalDateTime.now());quartzLogDto.setSpendTime(between.toMillis());quartzLogDto.setResult(1);quartzLogService.update(logId.get(), quartzLogDto);}@Overridepublic void execute(JobExecutionContext jobExecutionContext) {String clazz = this.getClass().getName();logger.info("==== 定时任务 "+clazz+" ====> 开启 " + DateUtil.getStringToday());beforeRun();try {runJob();} catch (Exception e) {logger.info("==== 定时任务 "+clazz+" ====> 异常 "+e.getMessage());error(e);} finally {logger.info("==== 定时任务 "+clazz+" ====> 结束 " + DateUtil.getStringToday());afterRun();}}
}

编写JpJobFactory继承从而创建单例Job进行注入。

package com.panda.common.crontask.web.schedule;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
public class JpJobFactory extends AdaptableJobFactory {@Autowiredprivate AutowireCapableBeanFactory capableBeanFactory;@Overrideprotected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {// 调用父类的方法Object jobInstance = super.createJobInstance(bundle);// 进行注入capableBeanFactory.autowireBean(jobInstance);return jobInstance;}
}

调度工厂类实现任务配置读取服务,项目启动激活所有定时任务,任务暂停,恢复,以及执行一次任务的方法。

package com.panda.common.crontask.web.schedule;
import com.panda.base.service.api.exception.ServiceException;
import com.panda.common.crontask.service.api.QuartzConfigService;
import com.panda.common.crontask.service.api.dto.QuartzConfigDto;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
/*** 调度工厂类**/
@Service
@Component
public class JpSchedulerFactory {private static Logger logger = LoggerFactory.getLogger(JpSchedulerFactory.class);@AutowiredSchedulerFactoryBean schedulerFactoryBean;// 任务配置读取服务@Autowiredprivate QuartzConfigService quartzConfigService;public void scheduleJobs() {Scheduler scheduler = getScheduler();startJob(scheduler);}// 获取schedulerprivate Scheduler getScheduler(){return schedulerFactoryBean.getScheduler();}// 项目启动,开启所有激活的任务private void startJob(Scheduler scheduler)  {try {// 获取所有激活的任务List<QuartzConfigDto> jobList = quartzConfigService.findByStatus(1);for (QuartzConfigDto config : jobList) {Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(config.getClazz());JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(config.getId()).build();CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(config.getCron());CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(config.getId()).withSchedule(scheduleBuilder).build();scheduler.scheduleJob(jobDetail, cronTrigger);}} catch (ClassNotFoundException e) {e.printStackTrace();}catch (SchedulerException e) {e.printStackTrace();}}// 任务暂停public void pauseJob(String id) throws SchedulerException {QuartzConfigDto quartzConfigDto = quartzConfigService.get(id);if(quartzConfigDto == null) throw new ServiceException(502,"不存在的任务");JobKey jobKey = JobKey.jobKey(id);Scheduler scheduler = getScheduler();scheduler.deleteJob(jobKey);}// 任务恢复public void resumeJob(String id) throws SchedulerException, ClassNotFoundException {QuartzConfigDto quartzConfigDto = quartzConfigService.get(id);if(quartzConfigDto == null) throw new ServiceException(502,"不存在的任务");JobKey jobKey = JobKey.jobKey(id);Scheduler scheduler = getScheduler();Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(quartzConfigDto.getClazz());JobDetail detail = scheduler.getJobDetail(jobKey);if (detail == null){JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(id).build();CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzConfigDto.getCron());CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(id).withSchedule(scheduleBuilder).build();scheduler.scheduleJob(jobDetail, cronTrigger);}else {scheduler.resumeJob(jobKey);}}// 执行一次任务public void runJob(String id) throws SchedulerException {QuartzConfigDto quartzConfigDto = quartzConfigService.get(id);if(quartzConfigDto == null) throw new ServiceException(502,"不存在的任务");JobKey jobKey = JobKey.jobKey(id);Scheduler scheduler = getScheduler();scheduler.triggerJob(jobKey);}
}

定时任务运行工厂类用来springboot启动监听和注入SchedulerFactoryBean

package com.panda.common.crontask.web.schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/*** 定时任务运行工厂类**/
@Configuration
public class StartSchedulerListener implements ApplicationListener<ContextRefreshedEvent> {@Autowiredpublic com.panda.common.crontask.web.schedule.JpSchedulerFactory jpSchedulerFactory;@Autowiredprivate com.panda.common.crontask.web.schedule.JpJobFactory jpJobFactory;// springboot 启动监听@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {jpSchedulerFactory.scheduleJobs();}//注入SchedulerFactoryBean@Beanpublic SchedulerFactoryBean schedulerFactoryBean() {SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();schedulerFactoryBean.setJobFactory(jpJobFactory);return schedulerFactoryBean;}
}

下面贴出api层代码

package com.panda.common.crontask.web.api;
import com.panda.auth.client.Authorization;
import com.panda.base.service.api.exception.ServiceException;
import com.panda.base.web.api.jersey.IResponse;
import com.panda.base.web.api.jersey.security.ISecurityContext;
import com.panda.base.web.api.response.WebApiResponse;
import com.panda.common.crontask.common.ApplicationConstants;
import com.panda.common.crontask.service.api.QuartzConfigService;
import com.panda.common.crontask.service.api.QuartzLogService;
import com.panda.common.crontask.service.api.dto.QuartzConfigDto;
import com.panda.common.crontask.service.api.dto.QuartzLogDto;
import com.panda.common.crontask.web.schedule.JpSchedulerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.time.LocalDateTime;
@Path("quartz")
@Component
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(tags = "【公共组件-定时任务】") 
@RolesAllowed("*")
@Authorization(permission = "quartz:*")
public class QuartzApi implements ISecurityContext, IResponse {private final static Logger log = LoggerFactory.getLogger(QuartzApi.class);@AutowiredQuartzConfigService quartzConfigService;@AutowiredQuartzLogService quartzLogService;//事务模版@Autowiredprivate TransactionTemplate transactionTemplate;@AutowiredJpSchedulerFactory JpSchedulerFactory;@ApiOperation(value = "获取任务分页")@GETpublic WebApiResponse<Page<QuartzConfigDto>> getQuartzConfigPage(@Context SecurityContext context,// 如果@Authorization存在,则不可缺少次参数。
@ApiParam(value = "页码(从0开始),默认0") @QueryParam("pageIndex") Integer pageIndex,
@ApiParam(value = "页大小,默认10") @QueryParam("pageSize") Integer pageSize,
@ApiParam(value = "任务名称") @QueryParam("name") String name,
@ApiParam(value = "任务状态 1-正常,0-停止") @QueryParam("status") Integer status) {if (pageIndex == null) pageIndex = 0;if (pageSize == null) pageSize = 10;Pageable pageable = PageRequest.of(pageIndex, pageSize,Sort.by(Sort.Direction.DESC, "updateTime"));return response(quartzConfigService.findQuartzConfigPage(status,name,pageable));}@ApiOperation(value = "通过Id获取任务详情")@GET@Path("{id}")public WebApiResponse<QuartzConfigDto> getQuartzConfigById(@Context SecurityContext context,@ApiParam(required = true, value = "quartzConfig Id") @PathParam("id") String id) {return response(quartzConfigService.get(id));}@ApiOperation(value = "通过类名获取任务详情")@GET@Path("getByClazz/{clazz}")public WebApiResponse<QuartzConfigDto> getQuartzConfigByClazz(@Context SecurityContext context,@ApiParam(required = true, value = "clazz") @PathParam("clazz") String clazz ) {return response(quartzConfigService.findByClazz(clazz));}@ApiOperation(value = "添加任务")@POST@Path("add")public WebApiResponse<QuartzConfigDto> addQuartzConfig(QuartzConfigDto quartzConfigDto, @Context SecurityContext context) {return response(quartzConfigService.addOrUpdateQuartzConfig(quartzConfigDto));}@ApiOperation(value = "删除任务")@POST@Path("delete/{id}")public WebApiResponse deleteQuartzConfig(@Context SecurityContext context, @ApiParam(required = true, value = "quartzConfig Id") @PathParam("id") String id) {return transactionTemplate.execute(new TransactionCallback<WebApiResponse>() {@Overridepublic WebApiResponse doInTransaction(TransactionStatus transactionStatus) {try {JpSchedulerFactory.pauseJob(id);quartzConfigService.delete(id);} catch (Exception e) {log.error("删除任务任务失败!", e);transactionStatus.setRollbackOnly();throw new ServiceException(502,"删除任务失败");}log.info("删除任务成功!");return done();}});}@ApiOperation(value = "更新任务")@POSTpublic WebApiResponse<QuartzConfigDto> updateQuartzConfig(QuartzConfigDto quartzConfigDto, @Context SecurityContext context) {try {JpSchedulerFactory.pauseJob(quartzConfigDto.getId());quartzConfigDto = quartzConfigService.updateQuartzConfig(quartzConfigDto);JpSchedulerFactory.resumeJob(quartzConfigDto.getId());} catch (Exception e) {log.error("更新任务失败!", e);throw new ServiceException(502,"暂停任务失败");}log.info("更新任务成功!");return response(quartzConfigDto);}@ApiOperation(value = "暂停任务")@GET@Path("pause/{id}")public WebApiResponse pauseQuartzConfig(@Context SecurityContext context, @ApiParam(required = true, value = "quartzConfig Id") @PathParam("id") String id) {return transactionTemplate.execute(new TransactionCallback<WebApiResponse>() {@Overridepublic WebApiResponse doInTransaction(TransactionStatus transactionStatus) {try {JpSchedulerFactory.pauseJob(id);quartzConfigService.updateJobStatus(id, ApplicationConstants.PAUSE_CODE);} catch (Exception e) {log.error("暂停任务失败!", e);transactionStatus.setRollbackOnly();throw new ServiceException(502,"暂停任务失败");}log.info("暂停任务成功!");return done();}});}@ApiOperation(value = "恢复任务")@GET@Path("resume/{id}")public WebApiResponse resumeQuartzConfig(@Context SecurityContext context, @ApiParam(required = true, value = "quartzConfig Id") @PathParam("id") String id) {return transactionTemplate.execute(new TransactionCallback<WebApiResponse>() {@Overridepublic WebApiResponse doInTransaction(TransactionStatus transactionStatus) {try {JpSchedulerFactory.resumeJob(id);quartzConfigService.updateJobStatus(id,ApplicationConstants.ACTIVE_CODE);} catch (Exception e) {log.error("恢复任务失败!", e);transactionStatus.setRollbackOnly();throw new ServiceException(502,"恢复任务失败");}log.info("恢复任务成功!");return done();}});}@ApiOperation(value = "执行一次任务")@GET@Path("run/{id}")public WebApiResponse runQuartzConfig(@Context SecurityContext context, @ApiParam(required = true, value = "quartzConfig Id") @PathParam("id") String id) {try {JpSchedulerFactory.runJob(id);} catch (Exception e) {log.error("执行任务失败!", e);throw new ServiceException(502,"执行任务失败");}log.info("执行任务成功!");return done();}@ApiOperation(value = "获取任务日志分页")@GET@Path("log")public WebApiResponse<Page<QuartzLogDto>> getQuartzLogPage(@Context SecurityContext context,@ApiParam(required = false, value = "页码(从0开始),默认0") @QueryParam("pageIndex") Integer pageIndex,@ApiParam(required = false, value = "页大小,默认10") @QueryParam("pageSize") Integer pageSize,@ApiParam(value = "任务Id") @QueryParam("quartzId") String quartzId,@ApiParam(value = "任务名称") @QueryParam("name") String name,@ApiParam(value = "执行结果 1-成功,0-失败") @QueryParam("result") Integer result,@ApiParam(value = "开始时间 yyyy-MM-dd 00:00:00") @QueryParam("startTime") LocalDateTime startTime,
@ApiParam(value = "结束时间 yyyy-MM-dd 00:00:00") @QueryParam("endTime") LocalDateTime endTime) {if (pageIndex == null) pageIndex = 0;if (pageSize == null) pageSize = 10;Pageable pageable = PageRequest.of(pageIndex, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));return response(quartzLogService.findQuartzLogPage(quartzId,name,result,startTime,endTime,pageable));}
}

执行实例

package com.panda.common.crontask.web.task;
import com.panda.common.crontask.web.schedule.JpJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/*** 定时任务实现类*/
@Component
@EnableScheduling
public class ScheduleTaskTestJob extends JpJob implements Serializable {private static Logger logger = LoggerFactory.getLogger(ScheduleTaskTestJob.class);/*** 执行任务** @throws RuntimeException*/@Overridepublic void runJob() throws RuntimeException {//在这里写定时任务执行的内容logger.info("==== 定时任务 ScheduleTaskTestJob ====> 执行中...... ");}
}

以上就是实现定时任务分布式组件的主要代码,写一个run模块集成一下数据库,做一个启动类就可以运行了,然后上传到neuxs做成依赖就可以供其他项目使用了,想看源码可以关注“蛋皮皮”公众号找大熊猫给你源码。

这篇关于大熊猫分布式组件开发系列教程(三)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/321235

相关文章

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Jenkins分布式集群配置方式

《Jenkins分布式集群配置方式》:本文主要介绍Jenkins分布式集群配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装jenkins2.配置集群总结Jenkins是一个开源项目,它提供了一个容易使用的持续集成系统,并且提供了大量的plugin满

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

SpringBoot开发中十大常见陷阱深度解析与避坑指南

《SpringBoot开发中十大常见陷阱深度解析与避坑指南》在SpringBoot的开发过程中,即使是经验丰富的开发者也难免会遇到各种棘手的问题,本文将针对SpringBoot开发中十大常见的“坑... 目录引言一、配置总出错?是不是同时用了.properties和.yml?二、换个位置配置就失效?搞清楚加

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

SpringBoot连接Redis集群教程

《SpringBoot连接Redis集群教程》:本文主要介绍SpringBoot连接Redis集群教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 依赖2. 修改配置文件3. 创建RedisClusterConfig4. 测试总结1. 依赖 <de

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间