600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > spring boot+mybatis+quartz项目的搭建

spring boot+mybatis+quartz项目的搭建

时间:2022-02-15 11:09:06

相关推荐

spring boot+mybatis+quartz项目的搭建

1. 因为这里我们是搭建spring boot+mybatis+quartz架构,故在pom.xml文件中配置相关依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.hzsun</groupId><artifactId>jobdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>jobdemo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId></dependency><!--&lt;!&ndash; druid数据库连接池 &ndash;&gt;--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2. spring boot的理念是做到零配置,所以这里没有web.xml,只有一个application.yml的配置,这个时配置数据源及mybatis的mapper扫描路径

server:port: 8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/db_quartz?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCusername: rootpassword: 1jpa:show-sql: truehibernate:ddl-auto: updatedatabase-platform: org.hibernate.dialect.MySQL5InnoDBDialectlogging:level:root: info

3. Spring boot web是不需要部署在Tomcat下的,因为自带了Tomcat,只需要执行主程序Application的main方法就可以了。但需要做些重要的配置

package org.tompai;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@SpringBootApplication@ServletComponentScanpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

这里的配置@SpringBootApplication是默认,注意第二个和第三个配置,如果缺少@MapperScan("com.hq.dispach.dao")配置则会出现dao无法注入到service的情况,如果@EnableAutoConfiguration缺少则会出现quartz任务调度里无法注入service,这里建议不管是什么应用程序都最好加上这个配置。

4 接下来就是control,service,dao,scheduleTask的代码编写了

Control:

package org.tompai.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.tompai.entity.JobEntity;import org.tompai.service.JobService;import java.util.List;/*** @desc : 任务controller*/@RestController@RequestMapping("job/")public class JobController {@Autowiredprivate JobService jobService;@RequestMapping("list")public List<JobEntity> list(){return jobService.findAll();}@RequestMapping("save")public String save(JobEntity jobEntity){try {jobService.save(jobEntity);return "成功";}catch (Exception e){return "失败";}}}

Sevice:

package org.tompai.service;import java.util.List;import org.tompai.entity.JobEntity;/*** @desc :*/public interface JobService {/*** 查询所有* @return 任务列表*/List<JobEntity> findAll();/*** 根据ID查询任务* @param id ID* @return*/JobEntity findById(String id);/*** 重试* @param jobEntity*/void reTry(JobEntity jobEntity);void deleteJob(String id);void save(JobEntity jobEntity);void update(JobEntity jobEntity);}

Dao:

package org.tompai.dao;import org.springframework.data.jpa.repository.JpaRepository;import org.tompai.entity.JobEntity;/*** @desc : 任务 仓储*/public interface JobDao extends JpaRepository<JobEntity,String> {}

ScheduleTask:

package org.tompai.utils;import org.quartz.JobExecutionContext;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.quartz.QuartzJobBean;import org.tompai.entity.JobEntity;import org.tompai.entity.JobLogEntity;import org.tompai.service.JobLogService;import org.tompai.service.JobService;import java.util.Date;import java.util.UUID;/*** 通用任务*/public class ScheduleJob extends QuartzJobBean {private Logger logger = LoggerFactory.getLogger(getClass());private static JobService jobService;private static JobLogService jobLogService;/*** 获取JobService 对象* @return JobService 对象*/private JobService getJobService(){if (jobService == null){jobService = (JobService) SpringContextUtil.getBean("jobServiceImpl");}return jobService;}/*** 获取日志service bean* @return 日志service*/private JobLogService getJobLogService(){if (jobLogService == null){jobLogService = (JobLogService) SpringContextUtil.getBean("jobLogServiceImpl");}return jobLogService;}@Overrideprotected void executeInternal(JobExecutionContext context) {JobEntity scheduleJob = (JobEntity) context.getMergedJobDataMap().get(JobEntity.JOB_PARAM_KEY);//任务开始时间long startTime = System.currentTimeMillis();JobLogEntity jobLogEntity = new JobLogEntity();jobLogEntity.setId(UUID.randomUUID().toString().replace("-",""));try {//执行任务logger.info("任务准备执行,任务ID:" + scheduleJob.getJobName());JobEntity jobEntity = this.getJobService().findById(scheduleJob.getId());jobLogEntity.setRanTime(new Date(startTime));if (jobEntity == null){//删除quartz 队列中的 任务this.getJobService().deleteJob(scheduleJob.getId());throw new RuntimeException("任务已经被删除");}//任务执行总时长long times = System.currentTimeMillis() - startTime;logger.info("任务执行完毕,任务ID:" + scheduleJob.getJobName() + " 总共耗时:" + times + "毫秒");jobLogEntity.setRanExpend(times);jobLogEntity.setStatus(0);jobLogEntity.setJobId(scheduleJob.getId());jobLogEntity.setRanNum(scheduleJob.getRetriedNum());} catch (Exception e) {logger.error("任务执行失败,任务ID:" + scheduleJob.getJobName(), e);jobLogEntity.setStatus(1);jobLogEntity.setMsg(e.getMessage());//需要重试if (scheduleJob.getRetry() == 1 && scheduleJob.getRestryNum() > scheduleJob.getRetriedNum()){logger.error("任务准备在" + scheduleJob.getRetryInterval() + "秒后重试。任务名:"+ scheduleJob.getJobName());this.getJobService().reTry(scheduleJob);}}finally {this.getJobLogService().save(jobLogEntity);}}}

Entity:

package org.tompai.entity;import org.hibernate.annotations.Proxy;import javax.persistence.Entity;import javax.persistence.Id;import java.io.Serializable;import java.util.Date;/*** @desc : 任务实体*/@Entity@Proxy(lazy = false)public class JobEntity implements Serializable {private static final long serialVersionUID = -8680221003366638822L;/*** 任务调度参数key*/public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";@Idprivate String id;/*** 任务名*/private String jobName;/*** 数据源ID*/private String sourceId;/*** 创建时间*/private Date createTime;/*** 当前状态: 1-正常,2-暂停,3-已删除*/private Integer status;/*** cron 表达式*/private String cronExpression;/*** 失败重试次数*/private int restryNum;/*** 是否失败重试 1-是,0 否*/private Integer retry;/*** 已经重试的次数*/private int retriedNum;/*** 重试间隔时间:单位-秒*/private int retryInterval;/*** 目标库ID*/private String targetId;/*** 重试时间,用于置0已重试次数。*/private Date retryDate;public Date getRetryDate() {return retryDate;}public void setRetryDate(Date retryDate) {this.retryDate = retryDate;}public int getRetryInterval() {return retryInterval;}public void setRetryInterval(int retryInterval) {this.retryInterval = retryInterval;}public String getTargetId() {return targetId;}public void setTargetId(String targetId) {this.targetId = targetId;}public String getJobName() {return jobName;}public void setJobName(String jobName) {this.jobName = jobName;}public String getSourceId() {return sourceId;}public void setSourceId(String sourceId) {this.sourceId = sourceId;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public String getCronExpression() {return cronExpression;}public void setCronExpression(String cronExpression) {this.cronExpression = cronExpression;}public int getRestryNum() {return restryNum;}public void setRestryNum(int restryNum) {this.restryNum = restryNum;}public Integer getRetry() {return retry;}public void setRetry(Integer retry) {this.retry = retry;}public int getRetriedNum() {return retriedNum;}public void setRetriedNum(int retriedNum) {this.retriedNum = retriedNum;}public String getId() {return id;}public void setId(String id) {this.id = id;}@Overridepublic String toString() {return "JobEntity{" +"id='" + id + '\'' +", jobName='" + jobName + '\'' +", sourceId='" + sourceId + '\'' +", createTime=" + createTime +", status=" + status +", cronExpression='" + cronExpression + '\'' +", restryNum=" + restryNum +", retry=" + retry +", retriedNum=" + retriedNum +", targetId='" + targetId + '\'' +'}';}}

5. 搭建好后启动application的main方法,通过页面访问control的URL可以获取数据库里的数据,同时quartz的定时任务会按照配置的时间定时执行

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。