spring-cloud分布式任务调度

2022-10-08  本文已影响0人  轻舞凋零

xxl-job的使用

1 配置服务

按照调度器

https://www.xuxueli.com/xxl-job/#2.1%20%E5%88%9D%E5%A7%8B%E5%8C%96%E2%80%9C%E8%B0%83%E5%BA%A6%E6%95%B0%E6%8D%AE%E5%BA%93%E2%80%9D

  1. 运行服务
  2. 配置执行器
  3. 配置bean

2 运行服务

    <dependency>
            <groupId>com.xuxueli</groupId>
            <artifactId>xxl-job-core</artifactId>
            <version>${xxl-job-core.verion}</version>
        </dependency>

配置
···
@Configuration
public class XxlJobConfig {
private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

@Value("${xxl.job.admin.addresses}")
private String adminAddresses;

@Value("${xxl.job.accessToken}")
private String accessToken;

@Value("${xxl.job.executor.appname}")
private String appname;

@Value("${xxl.job.executor.address}")
private String address;

@Value("${xxl.job.executor.ip}")
private String ip;

@Value("${xxl.job.executor.port}")
private int port;

@Value("${xxl.job.executor.logpath}")
private String logPath;

@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;


@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
    logger.info(">>>>>>>>>>> xxl-job config init.");
    XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
    xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
    xxlJobSpringExecutor.setAppname(appname);
    xxlJobSpringExecutor.setAddress(address);
    xxlJobSpringExecutor.setIp(ip);
    xxlJobSpringExecutor.setPort(port);
    xxlJobSpringExecutor.setAccessToken(accessToken);
    xxlJobSpringExecutor.setLogPath(logPath);
    xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
    return xxlJobSpringExecutor;
}

}
···

定时任务

@Data
@Slf4j
@Component
public class XxlCron {

    private static final String FORMAT_STR_TIME = "yyyy-MM-dd HH:mm:ss";

    private String currentTime = "";


    public static String getCurrentDateSimpleTpl() {
        return getCurrentDateSimpleTpl(FORMAT_STR_TIME, System.currentTimeMillis()/1000);
    }

    private static String getCurrentDateSimpleTpl(String tpl, long timestamp) {
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timestamp, 0, ZoneOffset.ofHours(8));
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(tpl);
        return localDateTime.format(formatter2);
    }




    @XxlJob("testRunXxl")
    public ReturnT<String> execute() {
        XxlJobHelper.log("XXL-JOB testRunXxl start");

        String currentTime = getCurrentDateSimpleTpl();

        log.info("currentTime:"+currentTime);
        this.currentTime = currentTime;
        return ReturnT.SUCCESS;
    }
}

调用服务代码

@Slf4j
@Api(tags={"用户接口"})
@RestController
public class UserController {


    @Autowired
    XxlCron xxlCron;


    @GetMapping("/info")
    public String configInfo2() {
        return xxlCron.getCurrentTime();
    }


}

运行服务
http://127.0.0.1:7190/info

上一篇 下一篇

猜你喜欢

热点阅读