依賴版本
JDK版本是:jdk17
springboot版本
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version></parent>
zookeeper
elasticjob 需要使用zookeeper為注冊中心
下載地址:https://zookeeper.apache.org/releases.html
下載后解壓,進入conf目錄
復制zoo_sample.cfg 文件,修改名稱為zoo.cfg,指定dataDir目錄
進入bin目錄,windows 點擊zkServer.cmd啟動,linux執行zkServer.sh文件啟動
elastic作業模式
elasticjob:regCenter:## 注冊中心serverLists: localhost:2181namespace: elasticjob-springbootjobs:simpleJob: elasticJobClass: xyz.toolhow.job.MyJobcron: 0 0/1 * * * ?timeZone: GMT+08:00shardingTotalCount: 3shardingItemParameters: 0=Beijing,1=Shanghai,2=GuangzhoudataflowJob:elasticJobClass: xyz.toolhow.job.SpringBootDataflowJobcron: 0 0/1 * * * ?timeZone: GMT+08:00shardingTotalCount: 3shardingItemParameters: 0=Beijing,1=Shanghai,2=Guangzhou
SimpleJob
@Component
public class MyJob implements SimpleJob {@Autowiredprivate OrderMapper orderMapper;@Overridepublic void execute(ShardingContext context) {
// System.out.println(context.getShardingItem());
// System.out.println(context.getShardingParameter());// 定時執行邏輯}
}
簡單任務可以分片執行,如果部分片,將并發執行,但是每次獲取全部數據進行執行,會導致內存問題所以進行以下優化
DataflowJob
@Component
public class SpringBootDataflowJob implements DataflowJob<Order> {@Autowiredprivate OrderMapper orderMapper;@Overridepublic List<Order> fetchData(final ShardingContext shardingContext) {List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>().eq(Order::getArea, shardingContext.getShardingParameter()).eq(Order::getStatus, 0).last("limit 10"));// 獲取數據return orders;}@Overridepublic void processData(final ShardingContext shardingContext, final List<Order> data) {for (Order order : data) {order.setStatus(1);orderMapper.updateById(order);System.out.println("----------------------------------");}}
}
使用該方式可以控制每次獲取數據的多少,降低內存壓力
強調一點,在修改配置后,最好刪除zookeeper節點,因為在實例注冊有緩存,容易導致配置失效,我在使用過程中,發生cron失效的問題,刪除zookeeper后,重啟生效