提升 Spring Boot 吞吐量的 7 个神技,让你的项目飞起来! ...

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

一、异步执行

实现方式二种:

  • 使用异步注解 @aysnc、启动类:添加 @EnableAsync 注解
  • JDK 8 本身有一个非常好用的 Future 类——CompletableFuture
  1. @AllArgsConstructor
  2. public class AskThread implements Runnable{
  3.     private CompletableFuture<Integer> re = null;
  4.     public void run() {
  5.         int myRe = 0;
  6.         try {
  7.             myRe = re.get() * re.get();
  8.         } catch (Exception e) {
  9.             e.printStackTrace();
  10.         }
  11.         System.out.println(myRe);
  12.     }
  13.     public static void main(String[] args) throws InterruptedException {
  14.         final CompletableFuture<Integer> future = new CompletableFuture<>();
  15.         new Thread(new AskThread(future)).start();
  16.         //模拟长时间的计算过程
  17.         Thread.sleep(1000);
  18.         //告知完成结果
  19.         future.complete(60);
  20.     }
  21. }
复制代码
在该示例中,启动一个线程,此时 AskThread 对象还没有拿到它需要的数据,执行到 myRe = re.get() * re.get() 会阻塞。
我们用休眠 1 秒来模拟一个长时间的计算过程,并将计算结果告诉 future 执行结果,AskThread 线程将会继续执行。
  1. public class Calc {
  2.     public static Integer calc(Integer para) {
  3.         try {
  4.             //模拟一个长时间的执行
  5.             Thread.sleep(1000);
  6.         } catch (InterruptedException e) {
  7.             e.printStackTrace();
  8.         }
  9.         return para * para;
  10.     }
  11.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  12.         final CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> calc(50))
  13.                 .thenApply((i) -> Integer.toString(i))
  14.                 .thenApply((str) -> """ + str + """)
  15.                 .thenAccept(System.out::println);
  16.         future.get();
  17.     }
  18. }
复制代码
CompletableFuture.supplyAsync 方法构造一个 CompletableFuture 实例,在 supplyAsync() 方法中,它会在一个新线程中,执行传入的参数。
在这里它会执行 calc() 方法,这个方法可能是比较慢的,但这并不影响 CompletableFuture 实例的构造速度,supplyAsync() 会立即返回。
而返回的 CompletableFuture 实例就可以作为这次调用的契约,在将来任何场合,用于获得最终的计算结果。
supplyAsync 用于提供返回值的情况,CompletableFuture 还有一个不需要返回值的异步调用方法 runAsync(Runnable runnable),一般我们在优化 Controller 时,使用这个方法比较多。
这两个方法如果在不指定线程池的情况下,都是在 ForkJoinPool.common 线程池中执行,而这个线程池中的所有线程都是 Daemon(守护)线程,所以,当主线程结束时,这些线程无论执行完毕都会退出系统。
核心代码:
  1. CompletableFuture.runAsync(() ->
  2.    this.afterBetProcessor(betRequest,betDetailResult,appUser,id)
  3. );
复制代码
异步调用使用 Callable 来实现:
  1. @RestController  
  2. public class HelloController {
  3.     private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
  4.     @Autowired  
  5.     private HelloService hello;
  6.     @GetMapping("/helloworld")
  7.     public String helloWorldController() {
  8.         return hello.sayHello();
  9.     }
  10.     /**
  11.      * 异步调用restful
  12.      * 当controller返回值是Callable的时候,springmvc就会启动一个线程将Callable交给TaskExecutor去处理
  13.      * 然后DispatcherServlet还有所有的spring拦截器都退出主线程,然后把response保持打开的状态
  14.      * 当Callable执行结束之后,springmvc就会重新启动分配一个request请求,然后DispatcherServlet就重新
  15.      * 调用和处理Callable异步执行的返回结果, 然后返回视图
  16.      *
  17.      * @return
  18.      */  
  19.     @GetMapping("/hello")
  20.     public Callable<String> helloController() {
  21.         logger.info(Thread.currentThread().getName() + " 进入helloController方法");
  22.         Callable<String> callable = new Callable<String>() {
  23.             @Override  
  24.             public String call() throws Exception {
  25.                 logger.info(Thread.currentThread().getName() + " 进入call方法");
  26.                 String say = hello.sayHello();
  27.                 logger.info(Thread.currentThread().getName() + " 从helloService方法返回");
  28.                 return say;
  29.             }
  30.         };
  31.         logger.info(Thread.currentThread().getName() + " 从helloController方法返回");
  32.         return callable;
  33.     }
  34. }
复制代码
异步调用的方式 WebAsyncTask:
  1. @RestController  
  2. public class HelloController {
  3.     private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
  4.     @Autowired  
  5.     private HelloService hello;
  6.         /**
  7.      * 带超时时间的异步请求 通过WebAsyncTask自定义客户端超时间
  8.      *
  9.      * @return
  10.      */  
  11.     @GetMapping("/world")
  12.     public WebAsyncTask<String> worldController() {
  13.         logger.info(Thread.currentThread().getName() + " 进入helloController方法");
  14.         // 3s钟没返回,则认为超时
  15.         WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(3000, new Callable<String>() {
  16.             @Override  
  17.             public String call() throws Exception {
  18.                 logger.info(Thread.currentThread().getName() + " 进入call方法");
  19.                 String say = hello.sayHello();
  20.                 logger.info(Thread.currentThread().getName() + " 从helloService方法返回");
  21.                 return say;
  22.             }
  23.         });
  24.         logger.info(Thread.currentThread().getName() + " 从helloController方法返回");
  25.         webAsyncTask.onCompletion(new Runnable() {
  26.             @Override  
  27.             public void run() {
  28.                 logger.info(Thread.currentThread().getName() + " 执行完毕");
  29.             }
  30.         });
  31.         webAsyncTask.onTimeout(new Callable<String>() {
  32.             @Override  
  33.             public String call() throws Exception {
  34.                 logger.info(Thread.currentThread().getName() + " onTimeout");
  35.                 // 超时的时候,直接抛异常,让外层统一处理超时异常
  36.                 throw new TimeoutException("调用超时");
  37.             }
  38.         });
  39.         return webAsyncTask;
  40.     }
  41.     /**
  42.      * 异步调用,异常处理,详细的处理流程见MyExceptionHandler类
  43.      *
  44.      * @return
  45.      */  
  46.     @GetMapping("/exception")
  47.     public WebAsyncTask<String> exceptionController() {
  48.         logger.info(Thread.currentThread().getName() + " 进入helloController方法");
  49.         Callable<String> callable = new Callable<String>() {
  50.             @Override  
  51.             public String call() throws Exception {
  52.                 logger.info(Thread.currentThread().getName() + " 进入call方法");
  53.                 throw new TimeoutException("调用超时!");
  54.             }
  55.         };
  56.         logger.info(Thread.currentThread().getName() + " 从helloController方法返回");
  57.         return new WebAsyncTask<>(20000, callable);
  58.     }
  59. }
复制代码
二、增加内嵌 Tomcat 的最大连接数


代码如下:
  1. @Configuration
  2. public class TomcatConfig {
  3.     @Bean
  4.     public ConfigurableServletWebServerFactory webServerFactory() {
  5.         TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
  6.         tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
  7.         tomcatFactory.setPort(8005);
  8.         tomcatFactory.setContextPath("/api-g");
  9.         return tomcatFactory;
  10.     }
  11.     class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer {
  12.         public void customize(Connector connector) {
  13.             Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
  14.             //设置最大连接数
  15.             protocol.setMaxConnections(20000);
  16.             //设置最大线程数
  17.             protocol.setMaxThreads(2000);
  18.             protocol.setConnectionTimeout(30000);
  19.         }
  20.     }
  21. }
复制代码


使用 @ComponentScan()


三、使用 @ComponentScan() 定位扫包

使用 @ComponentScan() 定位扫包比 @SpringBootApplication 扫包更快。

四、默认 Tomcat 容器改为 Undertow

默认 Tomcat 容器改为 Undertow(Jboss 下的服务器,Tomcat 吞吐量 5000,Undertow 吞吐量 8000)
  1. <exclusions>
  2.   <exclusion>
  3.      <groupId>org.springframework.boot</groupId>
  4.      <artifactId>spring-boot-starter-tomcat</artifactId>
  5.   </exclusion>
  6. </exclusions>
复制代码
改为:
  1. <dependency>
  2.   <groupId>org.springframework.boot</groupId>
  3.   <artifactId>spring-boot-starter-undertow</artifactId>
  4. </dependency>
复制代码
Spring Boot 基础就不介绍了,推荐下这个实战教程:https://github.com/javastacks/spring-boot-best-practice
五、使用 BufferedWriter 进行缓冲

这里不给大家举例,可自行尝试。
六、Deferred 方式实现异步调用

代码如下:
  1. @RestController
  2. public class AsyncDeferredController {
  3.     private final Logger logger = LoggerFactory.getLogger(this.getClass());
  4.     private final LongTimeTask taskService;
  5.     @Autowired
  6.     public AsyncDeferredController(LongTimeTask taskService) {
  7.         this.taskService = taskService;
  8.     }
  9.     @GetMapping("/deferred")
  10.     public DeferredResult<String> executeSlowTask() {
  11.         logger.info(Thread.currentThread().getName() + "进入executeSlowTask方法");
  12.         DeferredResult<String> deferredResult = new DeferredResult<>();
  13.         // 调用长时间执行任务
  14.         taskService.execute(deferredResult);
  15.         // 当长时间任务中使用deferred.setResult("world");这个方法时,会从长时间任务中返回,继续controller里面的流程
  16.         logger.info(Thread.currentThread().getName() + "从executeSlowTask方法返回");
  17.         // 超时的回调方法
  18.         deferredResult.onTimeout(new Runnable(){
  19.    @Override
  20.    public void run() {
  21.     logger.info(Thread.currentThread().getName() + " onTimeout");
  22.     // 返回超时信息
  23.     deferredResult.setErrorResult("time out!");
  24.    }
  25.   });
  26.         // 处理完成的回调方法,无论是超时还是处理成功,都会进入这个回调方法
  27.         deferredResult.onCompletion(new Runnable(){
  28.    @Override
  29.    public void run() {
  30.     logger.info(Thread.currentThread().getName() + " onCompletion");
  31.    }
  32.   });
  33.         return deferredResult;
  34.     }
  35. }
复制代码


七、异步调用可以使用 AsyncHandlerInterceptor 进行拦截



代码如下:
  1. @Component
  2. public class MyAsyncHandlerInterceptor implements AsyncHandlerInterceptor {
  3. private static final Logger logger = LoggerFactory.getLogger(MyAsyncHandlerInterceptor.class);
  4. @Override
  5. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
  6.    throws Exception {
  7.   return true;
  8. }
  9. @Override
  10. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
  11.    ModelAndView modelAndView) throws Exception {
  12. // HandlerMethod handlerMethod = (HandlerMethod) handler;
  13.   logger.info(Thread.currentThread().getName()+ "服务调用完成,返回结果给客户端");
  14. }
  15. @Override
  16. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
  17.    throws Exception {
  18.   if(null != ex){
  19.    System.out.println("发生异常:"+ex.getMessage());
  20.   }
  21. }
  22. @Override
  23. public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
  24.    throws Exception {
  25.   // 拦截之后,重新写回数据,将原来的hello world换成如下字符串
  26.   String resp = "my name is chhliu!";
  27.   response.setContentLength(resp.length());
  28.   response.getOutputStream().write(resp.getBytes());
  29.   logger.info(Thread.currentThread().getName() + " 进入afterConcurrentHandlingStarted方法");
  30. }
  31. }
复制代码
参考资料:
版权声明:本文为CSDN博主「灬点点」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/qq_32447301/article/details/88046026
近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2022最新版)
2.劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!
5.《Java开发手册(嵩山版)》最新发布,速速下载!
觉得不错,别忘了随手点赞+转发哦!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

千千梦丶琪

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表