Springboot項目中使用ElasticJob的小案例
序言
之前用線程中的ScheduledThreadPoolExecutor來做定時任務,由於這個可能會導致OOM,而最近使用springboot來做項目,就找了怎麼在Springboot項目中使用ElasticJob,所以自己經過實踐之後,特此記錄!
參考的博客有
1、SpringBoot使用Elastic-Job
2、Springboot整合Elastic-Job
由於是第一次學習將這2種技術整和到一起,所以大部分代碼都是借用的上面2位大神的~
感興趣的也可以看看官網
Elastic-Job官網地址:http://elasticjob.io/index_zh.html
Elastic-Job-Lite官方文檔地址:http://elasticjob.io/docs/elastic-job-lite/00-overview/intro/
關於介紹我就不多說了,可以自行查閱學習,直接步入正題啦~
一、工程目錄結構
二、配置文件
1、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ai</groupId>
<artifactId>ej-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ej-test</name>
<description>ej-test project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.properties
spring.application.name=ej-test
regCenter.serverList=0.0.0.0:2181,0.0.0.0:2182,0.0.0.0:2183
regCenter.namespace=springboot_elasticjob
stockJob.cron = 0/5 * * * * ?
stockJob.shardingTotalCount = 4
stockJob.shardingItemParameters = 0=0,1=1,2=0,3=1
說明:我在win10搭建了zookeeper,有3個節點
二、代碼部分
1、啓動類
package com.ai.ejt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EjTestApplication {
public static void main(String[] args) {
SpringApplication.run(EjTestApplication.class, args);
}
}
2、utils包
package com.ai.ejt.utils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeUtils {
public static String mill2Time(LocalDateTime localDateTime){
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String curTime=localDateTime.format(dateTimeFormatter);
return curTime;
}
}
3、MyElasticJobListener
package com.ai.ejt.listener;
import com.ai.ejt.utils.TimeUtils;
import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class MyElasticJobListener implements ElasticJobListener {
private static final Logger logger = LoggerFactory.getLogger(MyElasticJobListener.class);
private LocalDateTime localDateTime=LocalDateTime.now();
private Long beginTime = null;
@Override
public void beforeJobExecuted(ShardingContexts shardingContexts) {
beginTime=localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
String curTime= TimeUtils.mill2Time(localDateTime);
logger.info("===>{} JOB BEGIN TIME: {} <===",shardingContexts.getJobName(), curTime);
}
@Override
public void afterJobExecuted(ShardingContexts shardingContexts) {
LocalDateTime localDateTime=LocalDateTime.now();
Long endTime = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
String curTime= TimeUtils.mill2Time(localDateTime);
logger.info("===>{} JOB END TIME: {},TOTAL CAST: {} <===",shardingContexts.getJobName(), curTime, endTime - beginTime);
}
}
4、MySimpleJob
package com.ai.ejt.task;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class MySimpleJob implements SimpleJob {
Logger logger = LoggerFactory.getLogger(MySimpleJob.class);
@Override
public void execute(ShardingContext shardingContext) {
logger.info(String.format(
"Thread ID: %s, 作業分片總數: %s, " +
"當前分片項: %s.當前參數: %s," +
"作業名稱: %s.作業自定義參數: %s",
Thread.currentThread().getId(),
shardingContext.getShardingTotalCount(),
shardingContext.getShardingItem(),
shardingContext.getShardingParameter(),
shardingContext.getJobName(),
shardingContext.getJobParameter()
));
}
}
5、ZKRegisterConfig
package com.ai.ejt.config;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnExpression("'${regCenter.serverList}'.length() > 0")
public class ZKRegisterConfig {
@Bean(initMethod = "init")
public ZookeeperRegistryCenter regCenter(@Value("${regCenter.serverList}") final String serverList,
@Value("${regCenter.namespace}") final String namespace) {
return new ZookeeperRegistryCenter(new ZookeeperConfiguration(serverList, namespace));
}
}
6、ElasticJobConfig
package com.ai.ejt.config;
import com.ai.ejt.listener.MyElasticJobListener;
import com.ai.ejt.task.MySimpleJob;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticJobConfig {
@Autowired
private ZookeeperRegistryCenter regCenter;
/**
* 配置任務監聽器
* @return
*/
@Bean
public ElasticJobListener elasticJobListener() {
return new MyElasticJobListener();
}
/**
* 配置任務詳細信息
* @param jobClass
* @param cron
* @param shardingTotalCount
* @param shardingItemParameters
* @return
*/
private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass,
final String cron,
final int shardingTotalCount,
final String shardingItemParameters) {
//定義作業核心配置
JobCoreConfiguration jobCoreConfiguration=JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount)
.shardingItemParameters(shardingItemParameters).build();
// 定義SIMPLE類型配置
SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(jobCoreConfiguration, jobClass.getCanonicalName());
// 定義Lite作業根配置
LiteJobConfiguration liteJobConfiguration=LiteJobConfiguration.newBuilder(simpleJobConfig ).overwrite(true).build();
; return liteJobConfiguration;
}
@Bean(initMethod = "init")
public JobScheduler simpleJobScheduler(final MySimpleJob simpleJob,
@Value("${stockJob.cron}") final String cron,
@Value("${stockJob.shardingTotalCount}") final int shardingTotalCount,
@Value("${stockJob.shardingItemParameters}") final String shardingItemParameters) {
MyElasticJobListener elasticJobListener = new MyElasticJobListener();
return new SpringJobScheduler(simpleJob, regCenter,
getLiteJobConfiguration(simpleJob.getClass(), cron, shardingTotalCount, shardingItemParameters),
elasticJobListener);
}
}
最後控制檯的日誌
另外補充一下,
定時任務的表達式
秒(0~59)
分鐘(0~59)
小時(0~23)
天(月)(0~31,但是你需要考慮你月的天數)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)
其中每個元素可以是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。由於"月份中的日期"和"星期中的日期"這兩個元素互斥的,必須要對其中一個設置?.
0 0 10,14,16 * * ? 每天上午10點,下午2點,4點
0 0/30 9-17 * * ? 朝九晚五工作時間內每半小時
0 0 12 ? * WED 表示每個星期三中午12點
"0 0 12 * * ?" 每天中午12點觸發
"0 15 10 ? * *" 每天上午10:15觸發
"0 15 10 * * ?" 每天上午10:15觸發
"0 15 10 * * ? *" 每天上午10:15觸發
"0 15 10 * * ? 2005" 2005年的每天上午10:15觸發
"0 * 14 * * ?" 在每天下午2點到下午2:59期間的每1分鐘觸發
"0 0/5 14 * * ?" 在每天下午2點到下午2:55期間的每5分鐘觸發
"0 0/5 14,18 * * ?" 在每天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發
"0 0-5 14 * * ?" 在每天下午2點到下午2:05期間的每1分鐘觸發
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44觸發
"0 15 10 ? * MON-FRI" 週一至週五的上午10:15觸發
"0 15 10 15 * ?" 每月15日上午10:15觸發
"0 15 10 L * ?" 每月最後一日的上午10:15觸發
"0 15 10 ? * 6L" 每月的最後一個星期五上午10:15觸發
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最後一個星期五上午10:15觸發
"0 15 10 ? * 6#3" 每月的第三個星期五上午10:15觸發
有些子表達式能包含一些範圍或列表
例如:子表達式(天(星期))可以爲 “MON-FRI”,“MON,WED,FRI”,“MON-WED,SAT”
“*”字符代表所有可能的值
因此,“*”在子表達式(月)裏表示每個月的含義,“*”在子表達式(天(星期))表示星期的每一天
“/”字符用來指定數值的增量
例如:在子表達式(分鐘)裏的“0/15”表示從第0分鐘開始,每15分鐘
在子表達式(分鐘)裏的“3/20”表示從第3分鐘開始,每20分鐘(它和“3,23,43”)的含義一樣
“?”字符僅被用於天(月)和天(星期)兩個子表達式,表示不指定值
當2個子表達式其中之一被指定了值以後,爲了避免衝突,需要將另一個子表達式的值設爲“?”
“L” 字符僅被用於天(月)和天(星期)兩個子表達式,它是單詞“last”的縮寫
但是它在兩個子表達式裏的含義是不同的。
在天(月)子表達式中,“L”表示一個月的最後一天
在天(星期)自表達式中,“L”表示一個星期的最後一天,也就是SAT
如果在“L”前有具體的內容,它就具有其他的含義了
例如:“6L”表示這個月的倒數第6天,“FRIL”表示這個月的最一個星期五
注意:在使用“L”參數時,不要指定列表或範圍,因爲這會導致問題
最後還找到一篇整合了mysql的,有空我也去實踐一下,原文
與君共勉!!!