如何在SpringBoot中使用ElaticJob定时器

发布时间:2021-05-24 18:04:51 作者:Leah
来源:亿速云 阅读:160

如何在SpringBoot中使用ElaticJob定时器?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

POM文件配置

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>demojob</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>demojob</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <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>


    <!--elastic-job-->
    <dependency>
      <artifactId>elastic-job-common-core</artifactId>
      <groupId>com.dangdang</groupId>
      <version>2.1.5</version>
    </dependency>
    <dependency>
      <artifactId>elastic-job-lite-core</artifactId>
      <groupId>com.dangdang</groupId>
      <version>2.1.5</version>
    </dependency>
    <dependency>
      <artifactId>elastic-job-lite-spring</artifactId>
      <groupId>com.dangdang</groupId>
      <version>2.1.5</version>
    </dependency>
    <dependency>
      <artifactId>elastic-job-cloud-executor</artifactId>
      <groupId>com.dangdang</groupId>
      <version>2.1.5</version>
    </dependency>


    <!--mariadb-->
    <dependency>
      <groupId>org.mariadb.jdbc</groupId>
      <artifactId>mariadb-java-client</artifactId>
      <version>1.5.4</version>
    </dependency>
    <!--druid-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
    </dependency>
    <!--mybatis plus-->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatisplus-spring-boot-starter</artifactId>
      <version>1.0.5</version>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>2.1.9</version>
    </dependency>


  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

yaml文件配置(也可以用application.properties一样的)

# 配置配置数据源
spring:
 datasource:
  type: com.alibaba.druid.pool.DruidDataSource
  driver-class-name: org.mariadb.jdbc.Driver
  name: elastic-job-event
  url: jdbc:mariadb://127.0.0.1:3306/elasticjob
  username: root
  password: 123456
  druid:
   validationQuery: SELECT 1
   initialSize: 10
   minIdle: 10
   maxActive: 200
   minEvictableIdleTimeMillis: 180000
   testOnBorrow: false
   testWhileIdle: true
   removeAbandoned: true
   removeAbandonedTimeout: 1800
   logAbandoned: true
   poolPreparedStatements: true
   maxOpenPreparedStatements: 100

# 配置Zookeeper
regCenter:
 serverList: localhost:2181
 namespace: hulk_order_task

# 配置定时器规则
simpleJob:
 cron: 0/5 * * * * ?
 shardingTotalCount: 1
 shardingItemParameters: 0=1

开始写代码

RegistryCenterConfig

package com.example.demojob.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;

/**
 * 注册中心配置
 * 用于注册和协调作业分布式行为的组件,目前仅支持Zookeeper。
 * @author shudalei
 */
@Configuration
@ConditionalOnExpression("'${regCenter.serverList}'.length() > 0")
public class RegistryCenterConfig {
  @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));
  }
}

JobEventConfig

package com.example.demojob.config;

import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 如果想把作业运行的内容写到DB中,我们需要用到另一个构造器,
 * 同时定义自己的JobEventConfiguration,
 * 目前来说实现这个接口的只有一个类JobEventRdbConfiguration,
 * 通过这个可以将作业运行的痕迹进行持久化到DB的操作。
 * @author shudalei
 */
@Configuration
public class JobEventConfig {
  @Resource
  private DataSource dataSource;

  @Bean
  public JobEventConfiguration jobEventConfiguration() {
    return new JobEventRdbConfiguration(dataSource);
  }
}

SimpleJobConfig

package com.example.demojob.config;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
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 com.example.demojob.job.TestSimpleJob;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class SimpleJobConfig {

  /**
   * 注册中心
   */
  @Resource
  private ZookeeperRegistryCenter regCenter;
  /**
   * job事件配置
   */
  @Resource
  private JobEventConfiguration jobEventConfiguration;

  /**
   * 微信access token获取任务对象
   *
   */
  @Resource
  private TestSimpleJob simpleJob;

  /**
   *
   * @param cron 定时任务cron配置
   * @param shardingTotalCount 任务分片数
   * @param shardingItemParameters 任务分片参数
   * @return JobScheduler 任务调度器
   */
  @Bean(initMethod = "init")
  public JobScheduler simpleJobScheduler(@Value("${simpleJob.cron}") final String cron,
                      @Value("${simpleJob.shardingTotalCount}") final int shardingTotalCount,
                      @Value("${simpleJob.shardingItemParameters}") final String shardingItemParameters) {
    return new SpringJobScheduler(simpleJob, regCenter,
        getLiteJobConfiguration(simpleJob.getClass(), cron, shardingTotalCount, shardingItemParameters),
        jobEventConfiguration);
  }

  /**
   *
   * @param jobClass 任务调度类
   * @param cron 定时任务cron配置
   * @param shardingTotalCount 任务分片数
   * @param shardingItemParameters 任务分片参数
   * @return LiteJobConfiguration 任务配置
   */
  private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends com.dangdang.ddframe.job.api.simple.SimpleJob> jobClass, final String cron,
                             final int shardingTotalCount, final String shardingItemParameters) {
    return LiteJobConfiguration
        .newBuilder(
            new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount)
                .shardingItemParameters(shardingItemParameters).build(), jobClass.getCanonicalName()))
        .overwrite(true).build();
  }
}

TestSimpleJob,定时器任务本身

package com.example.demojob.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.stereotype.Component;

@Component
public class TestSimpleJob implements SimpleJob {

  private int count;
  //任务就是每5秒执行一次控制台输出1,2,3……
  @Override
  public void execute(ShardingContext shardingContext) {
    count++;
    System.out.println("task " + count);
  }
}

最后在Docker下安装 Zookeeper

安装脚本compose文件如下

version: '2'
services:
 zookeeper01:
  image: zookeeper
  restart: always
  hostname: zookeeper01
  ports:
   - 2181:2181
  environment:
   ZOO_MY_ID: 1
   ZOO_SERVERS: server.1=0.0.0.0:2888:3888 server.2=zookeeper02:2888:3888 server.3=zookeeper03:2888:3888
 zookeeper02:
  image: zookeeper
  restart: always
  hostname: zookeeper02
  ports:
   - 2182:2181
  environment:
   ZOO_MY_ID: 2
   ZOO_SERVERS: server.1=zookeeper01:2888:3888 server.2=0.0.0.0:2888:3888 server.3=zookeeper03:2888:3888
 zookeeper03:
  image: zookeeper
  restart: always
  hostname: zookeeper03
  ports:
   - 2183:2181
  environment:
   ZOO_MY_ID: 3
   ZOO_SERVERS: server.1=zookeeper01:2888:3888 server.2=zookeeper02:2888:3888 server.3=0.0.0.0:2888:3888

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

看完上述内容,你们掌握如何在SpringBoot中使用ElaticJob定时器的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 如如何使用journalctl命令?
  2. 如何在javascript中使用定时器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:怎么在Android中实现自动填写短信验证码

下一篇:如何在Android中嵌套滚动NestedScroll

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》