Java实现异步处理HTTP请求_方式一:通过Callable

超、凢脫俗 2023-07-21 08:49 121阅读 0赞

1、Callable

1)Runnable,执行独立的任务,但不返回值。如希望任务完成后有返回值,可以使用Callable接口实现;

2)Callable,是一个具有类型参数的范型,他的类型参数方法表示为方法call()而不是run()中返回的值,并且必须使用ExecutorService.submint()方法进行调用。

区别:

1.Callable,接受一个泛型,然后在call()方法中返回一个这个类型的值;然而,Runnable的run()方法无返回值;
2.Callable,其call()方法可抛出异常,而Runnable的run()方法是不抛出异常的。

2、业务场景:

  1. HTTP请求中,业务处理流程耗时较长,比如大的查询,远程调用等场景,接受http请求的主线程会被一直占用,而tomcat线程池线程数量又是有限的,所以,单位时间内接受http请求量就会下降。

3、代码示例

1)controller

  1. package com.liuxd.controller;
  2. import com.liuxd.entity.Responses;
  3. import com.liuxd.service.BusinessService;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.concurrent.Callable;
  9. @Slf4j
  10. @RestController
  11. public class AsyncCallableController {
  12. @Autowired
  13. private BusinessService businessService;
  14. @GetMapping(value = "/getData")
  15. public Callable<Responses<String>> getData() {
  16. log.info("收到HTTP请求...");
  17. Callable<Responses<String>> data = (() -> {
  18. return businessService.getData();
  19. });
  20. log.info("接收HTTP请求线程任务已完成,退出!");
  21. return data;
  22. }
  23. }

2、service

  1. package com.liuxd.service;
  2. import com.liuxd.entity.Responses;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.stereotype.Service;
  5. @Slf4j
  6. @Service
  7. public class BusinessService {
  8. public Responses<String> getData(){
  9. log.info("调用service方法,开始执行...");
  10. try {
  11. Thread.sleep(2500L);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. log.info("调用service方法,执行结束!!");
  16. return new Responses<>(0,"操作完成","SUCCESS");
  17. }
  18. }

3)打印结果

20200403104116867.png

发表评论

表情:
评论列表 (有 0 条评论,121人围观)

还没有评论,来说两句吧...

相关阅读