spring + quartz 分布式自定义注解
相关技术
本文采用spring + quartz的方案。使用mysql作为任务的持久化,支持分布式。
自定义注解
1.启用定时任务
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(QuartzConfig.class) //引入配置
@Documented
public @interface EnableMScheduling { } //该注解需要放在application启动类上,标识启用定时任务,它的作用就是配置、解析任务以及启动调
2.标识调度类
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface MScheduleClass { /**
* 任务分组,页面显示作用
* @return
*/
String module() default "系统"; /**
* 描述,提示作用
* @return
*/
String desc() default ""; }
//该注解放置在类上,标识指定的类是一组定时任务,其中需要设置任务分组,描述
3.标识执行的方法
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MSchedule { /**
* 任务名称
* @return
*/
String title() default ""; /**
* 调度触发的corn表达式 : 用作Job的触发器,目前只支持一个触发器表达式。
*/
String corn(); /**
* 描述
*/
String desc() default ""; /**
* 参数
*/
String param() default "";
}
//该注解标识在@MScheduleClass标识的类中的方法中,标识指定的方式是任务执行的方法。
配置类
import javax.sql.DataSource; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager; public class QuartzConfig { /**
* 配置任务调度器
* 使用项目数据源作为quartz数据源
* @param jobFactory 自定义配置任务工厂
* @param dataSource 数据源实例
* @return
* @throws Exception
*/
@Bean(destroyMethod = "destroy")
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource,
ObjectProvider<PlatformTransactionManager> transactionManager) throws Exception { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
// 项目启动完成后,等待10秒后开始执行调度器初始化
//schedulerFactoryBean.setStartupDelay(10);
// 设置调度器自动运行
schedulerFactoryBean.setAutoStartup(false);
// 设置数据源,使用与项目统一数据源
schedulerFactoryBean.setDataSource(dataSource); PlatformTransactionManager txManager = transactionManager.getIfUnique();
if (txManager != null) {
schedulerFactoryBean.setTransactionManager(txManager);
}
// 设置上下文spring bean name
schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
// 设置配置文件位置
schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
return schedulerFactoryBean;
} @Bean
public MScheduleBeanPostProcessor mScheduleBeanPostProcessor() {
return new MScheduleBeanPostProcessor();
}
}
其中dataSource我自己用的阿里的druid。 具体配置自行处理
quartz.properites
#调度器实例名称
org.quartz.scheduler.instanceName = quartzScheduler #调度器实例编号自动生成
org.quartz.scheduler.instanceId = AUTO #持久化方式配置
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX #持久化方式配置数据驱动,MySQL数据库
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate #quartz相关数据表前缀名
org.quartz.jobStore.tablePrefix = QRTZ_ #开启分布式部署
org.quartz.jobStore.isClustered = true
#配置是否使用
org.quartz.jobStore.useProperties = false #分布式节点有效性检查时间间隔,单位:毫秒
org.quartz.jobStore.clusterCheckinInterval = 20000 #线程池实现类
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool #执行最大并发线程数量
org.quartz.threadPool.threadCount = 10 #线程优先级
org.quartz.threadPool.threadPriority = 5 #配置是否启动自动加载数据库内的定时任务,默认true
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
quartz初始化的数据库表在org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql
注解解析beanPosrProcessor
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent; import com.mustr.cluster.annotation.MSchedule;
import com.mustr.cluster.annotation.MScheduleClass; import lombok.extern.slf4j.Slf4j; @Slf4j
public class MScheduleBeanPostProcessor implements BeanPostProcessor, ApplicationListener<ContextRefreshedEvent>, DisposableBean { @Autowired
private Scheduler scheduler; private List<MustrTask> tasks = new ArrayList<>(); @Override
public void destroy() throws Exception {
scheduler.shutdown();
} @Override
public void onApplicationEvent(ContextRefreshedEvent event) {
log.info("all scheduler tasks total {}", tasks.size()); try {
//先把原来的都删除
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
scheduler.deleteJobs(new ArrayList<>(jobKeys));
} catch (SchedulerException e1) {
e1.printStackTrace();
} //重新添加新的
tasks.forEach(task -> {
try {
scheduler.scheduleJob(task.getJobDetail(), task.getTrigger());
} catch (SchedulerException e) {
e.printStackTrace();
}
}); try {
scheduler.start(); //启动调度器
} catch (SchedulerException e) {
e.printStackTrace();
}
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
MScheduleClass msClass = bean.getClass().getAnnotation(MScheduleClass.class);
if (msClass == null) {
return bean;
} String group = bean.getClass().getSimpleName();
Method[] methods = bean.getClass().getDeclaredMethods();
if (methods == null) {
return bean;
} for (Method method : methods) {
MSchedule mSchedule = method.getAnnotation(MSchedule.class);
if (mSchedule == null) {
continue;
}
hanlderSchedule(group, mSchedule, method, bean);
} return bean;
} private void hanlderSchedule(String group, MSchedule mSchedule, Method method, Object bean) {
String jobName = method.getName(); JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("targetClass", bean);
jobDataMap.put("targetMethod", method.getName());
jobDataMap.put("arguments", mSchedule.param()); JobDetail jobDetail = JobBuilder.newJob(MustrCommonJob.class)
.setJobData(jobDataMap)
.withIdentity(new JobKey(jobName, group))
.withDescription(mSchedule.desc())
.storeDurably()
.build(); Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(new TriggerKey(jobName, group))
.withDescription(mSchedule.desc())
.withSchedule(CronScheduleBuilder.cronSchedule(mSchedule.corn()).withMisfireHandlingInstructionDoNothing())
.forJob(jobDetail)
.build(); tasks.add(new MustrTask(jobDetail, trigger));
}
}
该类就是解析自定义注解的@MScheduleClass和@MSchedule标识的任务。封装jobDetail和Trigger。
任务job统一使用MustrCommonJob通过反射来执行配置的指定类的指定方法
MustrTask
import org.quartz.JobDetail;
import org.quartz.Trigger; import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter; @Setter
@Getter
@AllArgsConstructor
public class MustrTask { private JobDetail jobDetail;
private Trigger trigger;
}
任务类
import java.io.Serializable; import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.MethodInvoker; public class MustrCommonJob implements Job, Serializable{
private static final long serialVersionUID = 8651275978441122356L; @Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Object targetClass = context.getMergedJobDataMap().get("targetClass");
String targetMethod = context.getMergedJobDataMap().getString("targetMethod");
String param = context.getMergedJobDataMap().getString("arguments"); //前置处理
// do .... try {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(targetClass);
methodInvoker.setTargetMethod(targetMethod);
if (param != null && !"".equals(param)) {
String[] params = param.split(",");
Object[] temp = new Object[params.length];
for (int i = 0; i < params.length; i++) {
temp[i] = params[i];
}
methodInvoker.setArguments(temp);
}
methodInvoker.prepare();
methodInvoker.invoke();
} catch (Exception e) {
e.printStackTrace();
} finally { //后置处理
// do ... 如记录日志
}
} }
该类实现了quartz的job接口。通过反射调用指定的方法
一个简单的demo
import java.io.Serializable;
import java.time.LocalDateTime; import com.mustr.cluster.annotation.MSchedule;
import com.mustr.cluster.annotation.MScheduleClass; @MScheduleClass(module = "系统", desc = "测试组")
public class HelloSchedule implements Serializable{
private static final long serialVersionUID = 3619058186885794136L; /*@MSchedule(corn = "0/30 * * * * ?", desc = "打印hello world")
public void hello() {
System.out.println("hello mustr..... <<<:::>>>" + LocalDateTime.now());
}*/ @MSchedule(corn = "0/10 * * * * ?", desc = "打印hello world")
public void hello1() {
System.out.println("<<<<hello1 mustr..... <<<:::>>>" + LocalDateTime.now());
}
}
最后一步
在程序启动类中加入 @EnableMScheduling注解,启动项目即可看到控制台打印
本文代码:https://github.com/Mustr/mustr-quartz-boot
spring + quartz 分布式自定义注解的更多相关文章
- spring quartz分布式任务计划
spring quartz分布式任务计划 环境: 通过maven管理的spring mvc工程,且已经成功连接数据库. 数据库表结构 /*Table structure for table `qrtz ...
- redis分布式锁-spring boot aop+自定义注解实现分布式锁
接这这一篇redis分布式锁-java实现末尾,实现aop+自定义注解 实现分布式锁 1.为什么需要 声明式的分布式锁 编程式分布式锁每次实现都要单独实现,但业务量大功能复杂时,使用编程式分布式锁无疑 ...
- 使用spring aspect控制自定义注解
自定义注解:这里是一个处理异常的注解,当调用方法发生异常时,返回异常信息 /** * ErrorCode: * * @author yangzhenlong * @since 2016/7/21 */ ...
- spring AOP 和自定义注解进行身份验证
一个SSH的项目(springmvc+hibernate),需要提供接口给app使用.首先考虑的就是权限问题,app要遵循极简模式,部分内容无需验证,用过滤器不能解决某些无需验证的方法 所以最终选择用 ...
- Spring实现封装自定义注解@Trimmed清除字符串前后的空格
在Spring中实现字符串清除的方法有很多,原生方法String自带trim()方法,或者使用StringUtils提供的trim...方法. 通常可以将上面的方式封装成自定义注解的形式去实现来节省更 ...
- Spring Boot中自定义注解+AOP实现主备库切换
摘要: 本篇文章的场景是做调度中心和监控中心时的需求,后端使用TDDL实现分表分库,需求:实现关键业务的查询监控,当用Mybatis查询数据时需要从主库切换到备库或者直接连到备库上查询,从而减小主库的 ...
- Spring Boot实现自定义注解
在Spring Boot项目中可以使用AOP实现自定义注解,从而实现统一.侵入性小的自定义功能. 实现自定义注解的过程也比较简单,只需要3步,下面实现一个统一打印日志的自定义注解: 1. 引入AOP依 ...
- spring boot通过自定义注解和AOP拦截指定的请求
一 准备工作 1.1 添加依赖 通过spring boot创建好工程后,添加如下依赖,不然工程中无法使用切面的注解,就无法对制定的方法进行拦截 <dependency> <group ...
- spring mvc实现自定义注解
实现方式:使用@Aspect实现: 1. 新建注解接口:CheckSign package com.soeasy.web.utils; import org.springframework.core. ...
随机推荐
- 使用Python虚拟环境
python 的虚拟环境可以为一个 python 项目提供独立的解释环境.依赖包等资源,既能够很好的隔离不同项目使用不同 python 版本带来的冲突,而且还能方便项目的发布. virtualenv ...
- 嗖嗖移动大厅 源代码 Java初级小项目
今天给大家一个比较综合的项目:嗖嗖移动业务大厅.项目功能很多,概括的功能也很全面.吃透了这个项目,你的java基础部分已经非常棒了!!! 一 . 项目概述 技能要求 使用面向对象设计的思想 合 ...
- php将富文本内容图片上传到oss并替换
/** * php 提取html中图片并替换 */ //要替换的内容 //提取图片路径的src的正则表达式 $match_str = '/(<img([^>]*)\s*src=(\'|\& ...
- linux: c语言 关闭标准输出STDOUT_FILENO对父子进程的影响
简介标准 I/O 库(stdio)及其头文件 stdio.h 为底层 I/O 系统调用提供了一个通用的接口.这个库现在已经成为 ANSI 标准 C 的一部分.标准 I/O 库提供了许多复杂的函数用于格 ...
- linux Netfilterr中扩展match target
Match: netfilter定义了一个通用的match数据结构struct xt_match /* 每个struct xt_match代表一个扩展match,netfilter中各个扩展match ...
- iscsi客户端常用操作
说明 本篇主要记录iscsi的客户端的一些常用的一些操作 iscsi服务端常用操作 删除一个lun tgtadm --lld iscsi --mode logicalunit --op delete ...
- ceph使用memdisk做journal
记得在很久很久以前,ceph当时的版本是有提供使用内存做journal的配置的,当时是使用的tmpfs,但是现在的版本在搜资料的时候,发现关于这个的没怎么找到资料,邮件列表里面有人有提到怎么做,看了下 ...
- springboot linux打包后访问不到resources 下面的模板文件
在本地是可以直接获取模板文件并下载,但是服务器上就不行 本地代码: @Overridepublic void downArchRelayTemplate(HttpServletRequest requ ...
- Android10_原理机制系列_Binder机制
前言 Binder 从java到c++到kernel,涉及的内容很多,很难在一篇文章中说清楚.这篇主要是自我记录,方便后续查询并拆分总结的. 因为涉及的的确非常多,不能面面俱到,所以可能一些地方感觉比 ...
- burp使用
只拦截特定网站数据包 我们以只拦截"www.baidu.com"为例 点击"Add"--布尔运算选择"And"--匹配类型选择"D ...