概要
众所周知,CompletableFuture
随着Java8的诞生粉墨登场,这个类提供了非常强大的Future
的扩展功能,可以大大简化我们进行异步编程时的复杂性以及代码的繁琐性,而且还是函数式的编码方式,可以通过各种静态方法对多个任务进行转换、计算以及组合最终收集;当然也可以进行任务的超时重试,这样就避开了对spring-retry
以及其他框架的依赖引入,既可以用来学习领悟,也能进行简单的任务超时重试处理。
前置知识
-
CompletableFuture
,本站有很多优秀文章,如下推荐一篇很喜欢的 -
线程池基础知识,以及对定时任务类型线程池
ThreadPoolTaskExecutor
基本了解,当然本文也会进行初步入门介绍
话不多说,下面是快速开始;show my code
引入
由于是写的demo版本,仅需要引入Spring
基础框架以及要求Jvm环境在1.8以上即可;
如有疑问或者错误,请大方指教,万分感谢
超时任务重试代码
/**
* @author zhangsx
* @description 简易的超时重试任务设计
* @date 2024-03-19 15:41:04
*/
public class LayZi {
public static void main(String[] args) {
ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(1);
ThreadPoolTaskExecutor taskExecutor = createExecutor();
taskExecutor.initialize();
//超时时间2s
long timeout = 2000L;
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Syst