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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

banq   2021-03-30 我要评论

前言

在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)来调用阻塞函数。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们