当前位置: 首页 > 工具软件 > x-simple-job > 使用案例 >

Elastic-Job-lite 3.x(一)demo

缑赤岩
2023-12-01

版本要求

依赖版本3.x
jdk1.8
maven3.5.0
zk3.6.0

zk 3.6.0搭建

docker run -e "ZOO_INIT_LIMIT=10" --name szk -p 2181:2181 -p 2888:2888 -p 3888:3888 -p 8080:8080  --restart always -d zookeeper

demo

依赖

<dependency>
    <groupId>org.apache.shardingsphere.elasticjob</groupId>
    <artifactId>elasticjob-lite-core</artifactId>
    <version>${latest.release.version}</version>
</dependency>

脚本代码

@Service
public class JobService implements SimpleJob {

  private int i = 0;

  @Override
  public void execute(ShardingContext shardingContext) {
    i++;
  }

}

与 spring 适配

maven 依赖

<dependency>
    <groupId>org.apache.shardingsphere.elasticjob</groupId>
    <artifactId>elasticjob-lite-spring-namespace</artifactId>
    <version>${latest.release.version}</version>
</dependency>

配置文件 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:elasticjob="http://shardingsphere.apache.org/schema/elasticjob"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://shardingsphere.apache.org/schema/elasticjob
                        http://shardingsphere.apache.org/schema/elasticjob/elasticjob.xsd
                        ">

  <!--配置作业注册中心,多个zk地址以逗号隔开 -->
<!--    server-lists="10.6.0.4:15311"-->
  <elasticjob:zookeeper id="regCenter"
    server-lists="127.0.0.1:2181"
    namespace="study-job"
    base-sleep-time-milliseconds="1000"
    max-sleep-time-milliseconds="3000"
    max-retries="3"/>

  <bean id="myJob" class="com.example.ejob.JobService" />

  <elasticjob:job
    id="job-2021"
    job-ref="myJob"
    registry-center-ref="regCenter"
    cron="0/5 * * * * ?"
    sharding-total-count="1"
  />

</beans>

适配 spring boot

maven 依赖

<dependency>
    <groupId>org.apache.shardingsphere.elasticjob</groupId>
    <artifactId>elasticjob-lite-spring-boot-starter</artifactId>
    <version>${latest.release.version}</version>
</dependency>

配置文件 application.yml

elasticjob:
  regCenter:
    serverLists: 127.0.0.1:2181
    namespace: study-job
  jobs:
    myJob:
      elasticJobClass: org.apache.shardingsphere.elasticjob.simple.job.SimpleJob
      cron: 0/5 * * * * ?
      shardingTotalCount: 1
 类似资料: