java springboot 初体验 (十三)对接esjob

  1. 上一篇
    1. java springboot 初体验 (十二)对接eureka
    2. https://www.cnblogs.com/zwjvzwj/p/16640193.html
  2. pom文件添加依赖
    1.   
      
              <!-- esjob 定时任务相关-->
              <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>
    2.   
  3.   application.properties或者application.yml添加配置
    1.   zookeeper的搭建,可以去网上找教程
      
      # esjob
      regCenter:
          serverList: zookeeper.xxxx:2181
          namespace: elasticjob-xxxx

       

  4.   ezookeeper相关
    1.   
      package com.zwj.core.configuration;
      
      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;
      
      /**
       * @ClassName: ZookeeperConfiguration
       * @Author zhangwujie
       * @Date 2022/8/30 9:34 下午
       * @Description: esjob的注册中心
       */
      @Configuration
      @ConditionalOnExpression("'${regCenter.serverList}'.length() > 0")
      public class EsJobRegistryCenterConfiguration {
      
          @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));
          }
      }
      

       

    2.  
  5.   定时任务编写
    1.   
      package com.zwj.core.esJob;
      
      import com.dangdang.ddframe.job.api.ShardingContext;
      import com.dangdang.ddframe.job.api.simple.SimpleJob;
      import lombok.extern.slf4j.Slf4j;
      
      /**
       * @ClassName: MyHelloJob
       * @Author zhangwujie
       * @Date 2022/8/31 10:26 上午
       * @Description:
       */
      @Slf4j
      public class MyHelloJob implements SimpleJob {
      
          @Override
          public void execute(ShardingContext shardingContext) {
              log.info(String.format("线程ID: %s," +
                              "线程名称: %s," +
                              "线程状态: %s," +
                              "线程是否活动状态: %s," +
                              "线程是否守护线程: %s," +
                              "线程是否中断: %s," +
                              "作业分片总数: %s, " +
                              "当前分片项: %s.当前参数: %s," +
                              "作业名称: %s.作业自定义参数: %s" +
                              ""
                      ,
                      Thread.currentThread().getId(),
                      Thread.currentThread().getName(),
                      Thread.currentThread().getState(),
                      Thread.currentThread().isAlive(),
                      Thread.currentThread().isDaemon(),
                      Thread.currentThread().isInterrupted(),
                      shardingContext.getShardingTotalCount(),
                      shardingContext.getShardingItem(),
                      shardingContext.getShardingParameter(),
                      shardingContext.getJobName(),
                      shardingContext.getJobParameter()
              ));
          }
      }

       

    2.    
  6.  定时任务修改链路追踪
    1.   
      package com.zwj.core.configuration;
      
      import com.dangdang.ddframe.job.api.ShardingContext;
      import com.dangdang.ddframe.job.api.simple.SimpleJob;
      import com.zwj.core.interceptor.TraceInterceptor;
      import lombok.extern.slf4j.Slf4j;
      import org.slf4j.MDC;
      
      import java.util.UUID;
      
      /**
       * @ClassName: SimpleJobStrategy
       * @Author zhangwujie
       * @Date 2022/8/31 9:28 下午
       * @Description:
       */
      @Slf4j
      public class SimpleJobStrategy implements SimpleJob {
      
          private static final String SEG = "-";
      
          private SimpleJob job;
      
          public SimpleJobStrategy(SimpleJob job) {
              this.job = job;
          }
      
          @Override
          public void execute(ShardingContext shardingContext) {
              try {
                  String opno = shardingContext.getJobName() + SEG +
                          shardingContext.getShardingTotalCount() + SEG +
                          shardingContext.getShardingItem() + SEG +
                          shardingContext.getShardingParameter() + SEG +
                          UUID.randomUUID();
      
                  MDC.put(TraceInterceptor.TRACE_ID, opno);
                  MDC.put(TraceInterceptor.SPAN_ID, UUID.randomUUID().toString());
      
                  job.execute(shardingContext);
                  MDC.clear();
      
              } catch (Exception e) {
                  log.error("SimpleJobStrategy catch error e={}", e.getMessage());
              }
          }
      }
      
    2.    
  7.  定时任务注册
    1.   
      package com.zwj.core.configuration;
      
      import com.dangdang.ddframe.job.api.ElasticJob;
      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.config.LiteJobConfiguration;
      import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
      import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
      import com.zwj.core.esJob.MyHelloJob;
      import lombok.extern.slf4j.Slf4j;
      import org.apache.commons.lang3.StringUtils;
      import org.springframework.beans.factory.config.BeanDefinition;
      import org.springframework.beans.factory.support.BeanDefinitionBuilder;
      import org.springframework.beans.factory.support.DefaultListableBeanFactory;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.ConfigurableApplicationContext;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      import javax.annotation.Resource;
      
      /**
       * @ClassName: EsJobConfiguration
       * @Author zhangwujie
       * @Date 2022/8/31 10:38 上午
       * @Description:
       */
      @Slf4j
      @Configuration
      public class EsJobMyHelloConfiguration {
          private final ZookeeperRegistryCenter regCenter;
      
          @Resource
          private ApplicationContext applicationContext;
      
          public EsJobMyHelloConfiguration(ZookeeperRegistryCenter regCenter) {
              this.regCenter = regCenter;
          }
      
          @Bean
          public SimpleJob stockJob() {
              return new MyHelloJob();
          }
      
          /**
           * elastic job在启动的时候需要注册bean schedule,调用init的方法,完成初始化配置信息
           *
           * @param simpleJob simpleJob
           * @return JobScheduler
           */
          @Bean(initMethod = "init")
          public JobScheduler esJobInitMyHelloJob(final SimpleJob simpleJob) {
      
              String esJobName = "MyHelloJob";
              String esJobClass = "com.zwj.core.esJob.MyHelloJob";
              String cron = "0 0/1 * * * ?";
              int shardingTotalCount = 3;
              String shardingItemParameters = "0=A,1=B,2=C";
              String jobParameters = "MyHelloJob";
      
              // 注册bean
              SimpleJob newSimpleJob = registerBean(
                      esJobName,
                      esJobClass,
                      SimpleJob.class
              );
      
              // 重写simpleJob?
              ElasticJob elasticJob = new SimpleJobStrategy(newSimpleJob);
      
              //向spring容器中注册作业任务
              return new SpringJobScheduler(
                      elasticJob,
                      regCenter,
                      getLiteJobConfiguration(
                              simpleJob.getClass(),
                              cron,
                              shardingTotalCount,
                              shardingItemParameters,
                              jobParameters
                      )
              );
          }
      
          private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass,
                                                               final String cron,
                                                               final int shardingTotalCount,
                                                               final String shardingItemParameters,
                                                               final String jobParameters) {
              // 定义作业核心配置
              JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount).
                      shardingItemParameters(shardingItemParameters).jobParameter(jobParameters).build();
              // 定义SIMPLE类型配置
              SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, jobClass.getCanonicalName());
              // 定义Lite作业根配置
              LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(true).build();
              return simpleJobRootConfig;
          }
      
          /**
           * 向spring容器中注册bean
           *
           * @param beanName            bean名字
           * @param strClass            类全路径
           * @param tClass              类类型
           * @param constructorArgValue 构造函数参数
           * @param <T>                 泛型
           * @return T
           */
          protected <T> T registerBean(String beanName, String strClass, Class<T> tClass, Object... constructorArgValue) {
      
              //判断是否配置了监听者
              if (StringUtils.isBlank(strClass)) {
                  return null;
              }
      
              if (StringUtils.isBlank(beanName)) {
                  beanName = strClass;
              }
      
              //判断监听者是否已经在spring容器中存在
              if (applicationContext.containsBean(beanName)) {
                  return applicationContext.getBean(beanName, tClass);
              }
      
              //不存在则创建并注册到Spring容器中
              BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(strClass);
              beanDefinitionBuilder.setScope(BeanDefinition.SCOPE_PROTOTYPE);
              //设置参数
              for (Object argValue : constructorArgValue) {
                  beanDefinitionBuilder.addConstructorArgValue(argValue);
              }
              DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
      
              defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
              return applicationContext.getBean(beanName, tClass);
          }
      
      }
      

       

    2.  
  8. 启动服务
  9. 查看日志
    1.   
  10. 下一篇
posted @ 2022-09-02 17:28  zwjvzwj  阅读(135)  评论(0编辑  收藏  举报