码迷,mamicode.com
首页 > 编程说话 > 详细

spring-boot-starter-quartz集群实际

时间:2019-08-11 01:16:51      浏览:225121      评论:0      收藏:0      [点我收藏+]

标签:str   use   pid   corn   时间表   获得参数   cond   training   rgs   

【**前情提纲**】由于项目须要,须要一个准时义务集群,故此有了这个spring-boot-starter-quartz集群的实际。springboot的版本为:2.1.6.RELEASE;quartz的版本为:2.3.1.假设这里一共有两个准时义务的节点,它们的代码完全一样。 --- # 壹.jar包依附 ~~~pom 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-quartz mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-jdbc org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test ~~~ 这里选择将准时义务的数据入库,防止数据直接存在内存中,因应用重启形成的数据损掉和做集群控制。 # 贰、项目设备 ~~~yaml spring: server: port: 8080 servlet: context-path: /lovin datasource: url: jdbc:mysql://127.0.0.1:3306/training?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver quartz: job-store-type: jdbc #数据库方法 jdbc: initialize-schema: never #不初始化表构造 properties: org: quartz: scheduler: instanceId: AUTO #默许主机名和时间戳生成实例ID,可所以任何字符串,但关于一切调剂法式榜样来讲,必须是唯一的 对应qrtz_scheduler_state INSTANCE_NAME字段 #instanceName: clusteredScheduler #quartzScheduler jobStore: class: org.quartz.impl.jdbcjobstore.JobStoreTX #耐久化设备 driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate #我们仅为数据库制造了特定于数据库的代理 useProperties: false #以指导JDBCJobStore将JobDataMaps中的一切值都作为字符串,是以可以作为称号 - 值对存储而不是在BLOB列中以其序列化情势存储更多复杂的对象。从长远来看,这是更安然的,由于您防止了将非String类序列化为BLOB的类版本成绩。 tablePrefix: qrtz_ #数据库表前缀 misfireThreshold: 60000 #在被认为“掉火”之前,调剂法式榜样将“容忍”一个Triggers将其下一个启动时间经过过程的毫秒数。默许值(假设您在设备中未输入此属性)为60000(60秒)。 clusterCheckinInterval: 5000 #设置此实例“检入”*与群集的其他实例的频率(以毫秒为单位)。影响检测掉败实例的速度。 isClustered: true #翻开群集功能 threadPool: #连接池 class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true ~~~ **这里须要留意的是两个节点的端标语应当不分歧,防止抵触** # 叁、完成一个Job ~~~java @Slf4j public class Job extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { // 获得参数 JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); // 营业逻辑 ... log.info("------springbootquartzonejob履行"+jobDataMap.get("name").toString()+"###############"+jobExecutionContext.getTrigger()); } ~~~ **个中的日记输入是为了便于不雅察义务履行情况** # 肆、封装准时义务操作 ~~~java @Service public class QuartzService { @Autowired private Scheduler scheduler; @PostConstruct public void startScheduler() { try { scheduler.start(); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 增长一个job * * @param jobClass * 义务虚现类 * @param jobName * 义务称号 * @param jobGroupName * 义务组名 * @param jobTime * 时间表达式 (这是每隔若干秒为一次义务) * @param jobTimes * 运转的次数 (<0:表示不限次数) * @param jobData * 参数 */ public void addJob(Class jobClass, String jobName, String jobGroupName, int jobTime, int jobTimes, Map jobData) { try { // 义务称号和组构成义务key JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName) .build(); // 设置job参数 if(jobData!= null && jobData.size()>0){ jobDetail.getJobDataMap().putAll(jobData); } // 应用simpleTrigger规矩 Trigger trigger = null; if (jobTimes < 0) { trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName) .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1).withIntervalInSeconds(jobTime)) .startNow().build(); } else { trigger = TriggerBuilder .newTrigger().withIdentity(jobName, jobGroupName).withSchedule(SimpleScheduleBuilder .repeatSecondlyForever(1).withIntervalInSeconds(jobTime).withRepeatCount(jobTimes)) .startNow().build(); } scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 增长一个job * * @param jobClass * 义务虚现类 * @param jobName * 义务称号(建议唯一) * @param jobGroupName * 义务组名 * @param jobTime * 时间表达式 (如:0/5 * * * * ? ) * @param jobData * 参数 */ public void addJob(Class jobClass, String jobName, String jobGroupName, String jobTime, Map jobData) { try { // 创建jobDetail实例,绑定Job完成类 // 指明job的称号,地点组的称号,和绑定job类 // 义务称号和组构成义务key JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName) .build(); // 设置job参数 if(jobData!= null && jobData.size()>0){ jobDetail.getJobDataMap().putAll(jobData); } // 定义调剂触发规矩 // 应用cornTrigger规矩 // 触发器key Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName) .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND)) .withSchedule(CronScheduleBuilder.cronSchedule(jobTime)).startNow().build(); // 把作业和触发器注册到义务调剂中 scheduler.scheduleJob(jobDetail, trigger); } catch (Exception e) { e.printStackTrace(); } } /** * 修改 一个job的 时间表达式 * * @param jobName * @param jobGroupName * @param jobTime */ public void updateJob(String jobName, String jobGroupName, String jobTime) { try { TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); trigger = trigger.getTriggerBuilder().withIdentity(triggerKey) .withSchedule(CronScheduleBuilder.cronSchedule(jobTime)).build(); // 重启触发器 scheduler.rescheduleJob(triggerKey, trigger); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 删除义务一个job * * @param jobName * 义务称号 * @param jobGroupName * 义务组名 */ public void deleteJob(String jobName, String jobGroupName) { try { scheduler.deleteJob(new JobKey(jobName, jobGroupName)); } catch (Exception e) { e.printStackTrace(); } } /** * 暂停一个job * * @param jobName * @param jobGroupName */ public void pauseJob(String jobName, String jobGroupName) { try { JobKey jobKey = JobKey.jobKey(jobName, jobGroupName); scheduler.pauseJob(jobKey); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 恢复一个job * * @param jobName * @param jobGroupName */ public void resumeJob(String jobName, String jobGroupName) { try { JobKey jobKey = JobKey.jobKey(jobName, jobGroupName); scheduler.resumeJob(jobKey); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 急速履行一个job * * @param jobName * @param jobGroupName */ public void runAJobNow(String jobName, String jobGroupName) { try { JobKey jobKey = JobKey.jobKey(jobName, jobGroupName); scheduler.triggerJob(jobKey); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 获得一切筹划中的义务列表 * * @return */ public List> queryAllJob() { List> jobList = null; try { GroupMatcher matcher = GroupMatcher.anyJobGroup(); Set jobKeys = scheduler.getJobKeys(matcher); jobList = new ArrayList>(); for (JobKey jobKey : jobKeys) { List triggers = scheduler.getTriggersOfJob(jobKey); for (Trigger trigger : triggers) { Map map = new HashMap<>(); map.put("jobName", jobKey.getName()); map.put("jobGroupName", jobKey.getGroup()); map.put("description", "触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); map.put("jobStatus", triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); map.put("jobTime", cronExpression); } jobList.add(map); } } } catch (SchedulerException e) { e.printStackTrace(); } return jobList; } /** * 获得一切正在运转的job * * @return */ public List> queryRunJob() { List> jobList = null; try { List executingJobs = scheduler.getCurrentlyExecutingJobs(); jobList = new ArrayList>(executingJobs.size()); for (JobExecutionContext executingJob : executingJobs) { Map map = new HashMap(); JobDetail jobDetail = executingJob.getJobDetail(); JobKey jobKey = jobDetail.getKey(); Trigger trigger = executingJob.getTrigger(); map.put("jobName", jobKey.getName()); map.put("jobGroupName", jobKey.getGroup()); map.put("description", "触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); map.put("jobStatus", triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); map.put("jobTime", cronExpression); } jobList.add(map); } } catch (SchedulerException e) { e.printStackTrace(); } return jobList; } ~~~ # 陆、初始化义务 这里不预备给用户用web界面来设备准时义务,故此采取**CommandLineRunner**来子啊应用初始化的时辰来初始化义务。只须要完成CommandLineRunner的run()办法便可。 ~~~java @Override public void run(String... args) throws Exception { HashMap map = new HashMap<>(); map.put("name",1); quartzService.deleteJob("job", "test"); quartzService.addJob(Job.class, "job", "test", "0 * * * * ?", map); map.put("name",2); quartzService.deleteJob("job2", "test"); quartzService.addJob(Job.class, "job2", "test", "10 * * * * ?", map); map.put("name",3); quartzService.deleteJob("job3", "test2"); quartzService.addJob(Job.class, "job3", "test2", "15 * * * * ?", map); } ~~~ # 柒、测实验证 分别夏侯启动两个应用,然后不雅察义务履行,和在运转过程当中杀逝世某个办事,来不雅察准时义务的履行。 ![SpringbootquartzoneApplication](https://img2018.cnblogs.com/blog/1035487/201908/1035487-20190810230438049-1371830870.png) ![SpringbootquartztwoApplication](https://img2018.cnblogs.com/blog/1035487/201908/1035487-20190810230443158-660952439.png) 【**写在前面的话**】下面给出的是所须要脚本的连接地址:[脚本下载地址](http://www.quartz-scheduler.org/downloads/),别的这边又一个本身完成的[demo](https://github.com/eelve/springbootquartzs.git)

spring-boot-starter-quartz集群实际

标签:str   use   pid   corn   时间表   获得参数   cond   training   rgs   

原文地址:https://www.cnblogs.com/eelve/p/11333399.html

(0)
(0)
   
告发
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权一切 京ICP备13008772号-2
迷上了代码!