在Spring Boot2中使用CompletableFuture的方法教程

作者:banq 时间:2022-09-27 14:18:51 

前言

在Spring Boot中有一个注释@Async,可以帮助开发人员开发并发应用程序。但使用此功能非常棘手。在本博客中,我们将了解如何将此功能与CompletableFuture一起使用。我认为你已经知道关于CompletableFuture的基础,所以我不会在这里重复这个概念。

首先,您需要使用@EnableAsync来注释您的应用程序类,这个注释告诉Spring查找使用@Async注释的方法并在单独的执行程序中运行它们。


@SpringBootApplication
@EnableAsync
public class App {
RestTemplate
public static void main(String[] args) {
 SpringApplication.run(App.class, args);
}
}

如果您查看有关使用CompletableFuture和@Async的Spring Boot示例,您会注意到他们使用此功能的方式基于REST请求,在我看来,我相信,它有点受限,它不会给你在其他情况下如何使用此功能的线索。例如,如果你有一个长期运行的任务,你会怎么做?


// Source : https://spring.io/guides/gs/async-method/
package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;

@Service
public class GitHubLookupService {

private static final Logger logger = LoggerFactory.getLogger(GitHubLookupService.class);

private final RestTemplate restTemplate;

public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) {
   this.restTemplate = restTemplateBuilder.build();
 }

@Async
 public CompletableFuture<User> findUser(String user) throws InterruptedException {
   logger.info("Looking up " + user);
   String url = String.format("https://api.github.com/users/%s", user);
   User results = restTemplate.getForObject(url, User.class);
   // Artificial delay of 1s for demonstration purposes
   Thread.sleep(1000L);
   return CompletableFuture.completedFuture(results);
 }

}

在FindUser(String user)中,它在主线程中使用CompletableFuture,此方法的主要任务是使用RestTemplate从github获取数据,功能是“执行HTTP请求的同步客户端”。如何使用长时间运行的任务,如调用网络功能,如从REST端点ping服务器?在这种情况下,您需要定制CompletableFuture。你不能简单地调用:


return CompletableFuture.completedFuture(results);

如何使用CompletableFuture

要在代码中使用@Async,您的方法必须返回Future或CompletableFuture,看一下下面的例子:


@Async
 public CompletableFuture<Boolean> isServerAlive(String ip) {
   CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(){
     @Override
     public Boolean get() throws InterruptedException, ExecutionException {
       InetAddress address = null;
       try {
         address = InetAddress.getByName(ip);
         return address.isReachable(1000);
       } catch (UnknownHostException e) {
         e.printStackTrace();
         return false;
       } catch (IOException e) {
         e.printStackTrace();
         return false;
       }
     }
   };
   return future;
}

在这个例子中,我重写了get()方法并返回CompletableFuture而没有任何线程执行器,事实上我们要求Spring在不同的线程中执行@Async方法,但是我们不提供任何线程执行器,只有后台工作者中运行就足够了。

download source code from github (本地下载)

注意:在这个例子中,我决定在Spring Boot中使用一个网络函数,仅仅是为了一个参数。但最好不要在REST端点中直接使用网络功能,特别是当您希望立即获得结果时。原因是:网络功能是阻塞的,这意味着,如果你调用这个REST端点,您必须在端点等待获取结果。强烈建议使用其他方法(如queue或push方法)(例如websocket)来调用阻塞函数。

来源:https://www.jdon.com/51288

标签:springboot2,completablefuture
0
投稿

猜你喜欢

  • SpringBoot整合SpringTask实现定时任务的流程

    2022-03-28 22:24:40
  • C# Bitmap 复制的小例子

    2023-01-19 12:49:39
  • SpringBoot工程打包与运行的实现详解

    2023-11-10 23:51:28
  • 详解maven中profiles使用实现

    2022-11-13 23:14:24
  • JAVA实现301永久重定向方法

    2023-12-18 10:59:08
  • 使用GSON库将Java中的map键值对应结构对象转换为JSON

    2022-10-21 14:51:47
  • Java金额大小写的转换方法

    2023-08-23 00:26:11
  • bool当成函数参数错误理解

    2021-07-30 09:27:18
  • c#实现16进制和字符串之间转换的代码

    2023-07-22 08:28:09
  • Java8新特性之泛型的目标类型推断_动力节点Java学院整理

    2023-11-26 10:38:21
  • 详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

    2022-09-20 04:41:04
  • mybatis注入Date日期值为null的解决方法

    2021-12-08 01:49:17
  • MAC下如何设置JDK环境变量

    2023-12-20 16:05:24
  • Android中外接键盘的检测的实现

    2023-07-27 21:15:13
  • C#推送信息到APNs的方法

    2023-05-29 05:20:59
  • springBoot集成Elasticsearch 报错 Health check failed的解决

    2022-12-07 05:18:16
  • 详解Java双轴快速排序算法

    2023-10-05 15:50:14
  • Android Rxjava3 使用场景详解

    2023-08-06 08:58:50
  • Springboot集成JSR303参数校验的方法实现

    2023-02-06 06:34:44
  • Android 6.0动态权限申请教程

    2023-09-26 16:43:56
  • asp之家 软件编程 m.aspxhome.com