1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        7 種提升 Spring Boot 吞吐量神技!

        共 18527字,需瀏覽 38分鐘

         ·

        2023-01-04 02:32

        關(guān)注我們,設(shè)為星標(biāo),每天7:40不見不散,架構(gòu)路上與您共享

        回復(fù)架構(gòu)師獲取資源


        大家好,我是你們的朋友架構(gòu)君,一個會寫代碼吟詩的架構(gòu)師。

        'javajgs.com';


        一、異步執(zhí)行

        實現(xiàn)方式二種:

        1. 使用異步注解@aysnc、啟動類:添加@EnableAsync注解
        2. JDK 8本身有一個非常好用的Future類——CompletableFuture
        @AllArgsConstructor
        public class AskThread implements Runnable{
            private CompletableFuture<Integer> re = null;

            public void run() {
                int myRe = 0;
                try {
                    myRe = re.get() * re.get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(myRe);
            }

            public static void main(String[] args) throws InterruptedException {
                final CompletableFuture<Integer> future = new CompletableFuture<>();
                new Thread(new AskThread(future)).start();
                //模擬長時間的計算過程
                Thread.sleep(1000);
                //告知完成結(jié)果
                future.complete(60);
            }
        }

        在該示例中,啟動一個線程,此時AskThread對象還沒有拿到它需要的數(shù)據(jù),執(zhí)行到 myRe = re.get() * re.get()會阻塞。我們用休眠1秒來模擬一個長時間的計算過程,并將計算結(jié)果告訴future執(zhí)行結(jié)果,AskThread線程將會繼續(xù)執(zhí)行。如果您正在學(xué)習(xí)Spring Boot,那么推薦一個連載多年還在繼續(xù)更新的免費教程:http://blog.didispace.com/spring-boot-learning-2x/

        public class Calc {
            public static Integer calc(Integer para) {
                try {
                    //模擬一個長時間的執(zhí)行
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return para * para;
            }

            public static void main(String[] args) throws ExecutionException, InterruptedException {
                final CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> calc(50))
                        .thenApply((i) -> Integer.toString(i))
                        .thenApply((str) -> "\"" + str + "\"")
                        .thenAccept(System.out::println);
                future.get();
            }
        }

        CompletableFuture.supplyAsync方法構(gòu)造一個CompletableFuture實例,在supplyAsync()方法中,它會在一個新線程中,執(zhí)行傳入的參數(shù)。在這里它會執(zhí)行calc()方法,這個方法可能是比較慢的,但這并不影響CompletableFuture實例的構(gòu)造速度,supplyAsync()會立即返回。

        而返回的CompletableFuture實例就可以作為這次調(diào)用的契約,在將來任何場合,用于獲得最終的計算結(jié)果。最近整理了一份最新的面試資料,里面收錄了2021年各個大廠的面試題,打算跳槽的小伙伴不要錯過,點擊領(lǐng)取吧!

        supplyAsync用于提供返回值的情況,CompletableFuture還有一個不需要返回值的異步調(diào)用方法runAsync(Runnable runnable),一般我們在優(yōu)化Controller時,使用這個方法比較多。這兩個方法如果在不指定線程池的情況下,都是在ForkJoinPool.common線程池中執(zhí)行,而這個線程池中的所有線程都是Daemon(守護)線程,所以,當(dāng)主線程結(jié)束時,這些線程無論執(zhí)行完畢都會退出系統(tǒng)。

        核心代碼:

        CompletableFuture.runAsync(() ->
           this.afterBetProcessor(betRequest,betDetailResult,appUser,id)
        );

        異步調(diào)用使用Callable來實現(xiàn)

        @RestController  
        public class HelloController {
          
            private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
              
            @Autowired  
            private HelloService hello;
          
            @GetMapping("/helloworld")
            public String helloWorldController() {
                return hello.sayHello();
            }
          
            /**
             * 異步調(diào)用restful
             * 當(dāng)controller返回值是Callable的時候,springmvc就會啟動一個線程將Callable交給TaskExecutor去處理
             * 然后DispatcherServlet還有所有的spring攔截器都退出主線程,然后把response保持打開的狀態(tài)
             * 當(dāng)Callable執(zhí)行結(jié)束之后,springmvc就會重新啟動分配一個request請求,然后DispatcherServlet就重新
             * 調(diào)用和處理Callable異步執(zhí)行的返回結(jié)果, 然后返回視圖
             *
             * @return
             */
          
            @GetMapping("/hello")
            public Callable<String> helloController() {
                logger.info(Thread.currentThread().getName() + " 進入helloController方法");
                Callable<String> callable = new Callable<String>() {
          
                    @Override  
                    public String call() throws Exception {
                        logger.info(Thread.currentThread().getName() + " 進入call方法");
                        String say = hello.sayHello();
                        logger.info(Thread.currentThread().getName() + " 從helloService方法返回");
                        return say;
                    }
                };
                logger.info(Thread.currentThread().getName() + " 從helloController方法返回");
                return callable;
            }
        }

        異步調(diào)用的方式 WebAsyncTask

        @RestController  
        public class HelloController {
          
            private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
              
            @Autowired  
            private HelloService hello;
          
                /**
             * 帶超時時間的異步請求 通過WebAsyncTask自定義客戶端超時間
             *
             * @return
             */
          
            @GetMapping("/world")
            public WebAsyncTask<String> worldController() {
                logger.info(Thread.currentThread().getName() + " 進入helloController方法");
          
                // 3s鐘沒返回,則認(rèn)為超時
                WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(3000, new Callable<String>() {
          
                    @Override  
                    public String call() throws Exception {
                        logger.info(Thread.currentThread().getName() + " 進入call方法");
                        String say = hello.sayHello();
                        logger.info(Thread.currentThread().getName() + " 從helloService方法返回");
                        return say;
                    }
                });
                logger.info(Thread.currentThread().getName() + " 從helloController方法返回");
          
                webAsyncTask.onCompletion(new Runnable() {
          
                    @Override  
                    public void run() {
                        logger.info(Thread.currentThread().getName() + " 執(zhí)行完畢");
                    }
                });
          
                webAsyncTask.onTimeout(new Callable<String>() {
          
                    @Override  
                    public String call() throws Exception {
                        logger.info(Thread.currentThread().getName() + " onTimeout");
                        // 超時的時候,直接拋異常,讓外層統(tǒng)一處理超時異常
                        throw new TimeoutException("調(diào)用超時");
                    }
                });
                return webAsyncTask;
            }
          
            /**
             * 異步調(diào)用,異常處理,詳細(xì)的處理流程見MyExceptionHandler類
             *
             * @return
             */
          
            @GetMapping("/exception")
            public WebAsyncTask<String> exceptionController() {
                logger.info(Thread.currentThread().getName() + " 進入helloController方法");
                Callable<String> callable = new Callable<String>() {
          
                    @Override  
                    public String call() throws Exception {
                        logger.info(Thread.currentThread().getName() + " 進入call方法");
                        throw new TimeoutException("調(diào)用超時!");
                    }
                };
                logger.info(Thread.currentThread().getName() + " 從helloController方法返回");
                return new WebAsyncTask<>(20000, callable);
            }
          
        }
        二、增加內(nèi)嵌Tomcat的最大連接數(shù)
        @Configuration
        public class TomcatConfig {
            @Bean
            public ConfigurableServletWebServerFactory webServerFactory() {
                TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
                tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
                tomcatFactory.setPort(8005);
                tomcatFactory.setContextPath("/api-g");
                return tomcatFactory;
            }
            class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer {
                public void customize(Connector connector) {
                    Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
                    //設(shè)置最大連接數(shù)
                    protocol.setMaxConnections(20000);
                    //設(shè)置最大線程數(shù)
                    protocol.setMaxThreads(2000);
                    protocol.setConnectionTimeout(30000);
                }
            }

        }


        三、使用@ComponentScan()定位掃包比@SpringBootApplication掃包更快
        四、默認(rèn)tomcat容器改為Undertow(Jboss下的服務(wù)器,Tomcat吞吐量5000,Undertow吞吐量8000)
        <exclusions>
          <exclusion>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-tomcat</artifactId>
          </exclusion>
        </exclusions>


        改為:

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        五、使用 BufferedWriter 進行緩沖
        六、Deferred方式實現(xiàn)異步調(diào)用
        @RestController
        public class AsyncDeferredController {
            private final Logger logger = LoggerFactory.getLogger(this.getClass());
            private final LongTimeTask taskService;
            
            @Autowired
            public AsyncDeferredController(LongTimeTask taskService) {
                this.taskService = taskService;
            }
            
            @GetMapping("/deferred")
            public DeferredResult<String> executeSlowTask() {
                logger.info(Thread.currentThread().getName() + "進入executeSlowTask方法");
                DeferredResult<String> deferredResult = new DeferredResult<>();
                // 調(diào)用長時間執(zhí)行任務(wù)
                taskService.execute(deferredResult);
                // 當(dāng)長時間任務(wù)中使用deferred.setResult("world");這個方法時,會從長時間任務(wù)中返回,繼續(xù)controller里面的流程
                logger.info(Thread.currentThread().getName() + "從executeSlowTask方法返回");
                // 超時的回調(diào)方法
                deferredResult.onTimeout(new Runnable(){
          
           @Override
           public void run() {
            logger.info(Thread.currentThread().getName() + " onTimeout");
            // 返回超時信息
            deferredResult.setErrorResult("time out!");
           }
          });
                
                // 處理完成的回調(diào)方法,無論是超時還是處理成功,都會進入這個回調(diào)方法
                deferredResult.onCompletion(new Runnable(){
          
           @Override
           public void run() {
            logger.info(Thread.currentThread().getName() + " onCompletion");
           }
          });
                
                return deferredResult;
            }
        }


        七、異步調(diào)用可以使用AsyncHandlerInterceptor進行攔截

        @Component
        public class MyAsyncHandlerInterceptor implements AsyncHandlerInterceptor {
         
         private static final Logger logger = LoggerFactory.getLogger(MyAsyncHandlerInterceptor.class);
         
         @Override
         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
           throws Exception
        {
          return true;
         }
         
         @Override
         public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
           ModelAndView modelAndView)
         throws Exception
        {
        // HandlerMethod handlerMethod = (HandlerMethod) handler;
          logger.info(Thread.currentThread().getName()+ "服務(wù)調(diào)用完成,返回結(jié)果給客戶端");
         }
         
         @Override
         public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
           throws Exception
        {
          if(null != ex){
           System.out.println("發(fā)生異常:"+ex.getMessage());
          }
         }
         
         @Override
         public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
           throws Exception
        {
          
          // 攔截之后,重新寫回數(shù)據(jù),將原來的hello world換成如下字符串
          String resp = "my name is chhliu!";
          response.setContentLength(resp.length());
          response.getOutputStream().write(resp.getBytes());
          
          logger.info(Thread.currentThread().getName() + " 進入afterConcurrentHandlingStarted方法");
         }
         
        }


        參考
        • https://my.oschina.net/u/3768341/blog/3001731

        • https://blog.csdn.net/liuchuanhong1/article/details/78744138

        來源:https://xhcom.blog.csdn.net/article/details/88046026

        到此文章就結(jié)束了。Java架構(gòu)師必看一個集公眾號、小程序、網(wǎng)站(3合1的文章平臺,給您架構(gòu)路上一臂之力,javajgs.com)。如果今天的文章對你在進階架構(gòu)師的路上有新的啟發(fā)和進步,歡迎轉(zhuǎn)發(fā)給更多人。歡迎加入架構(gòu)師社區(qū)技術(shù)交流群,眾多大咖帶你進階架構(gòu)師,在后臺回復(fù)“加群”即可入群。

        第25期已結(jié)束!第26期已開始,1月1號截止





        這些年小編給你分享過的干貨


        1.idea永久激活碼(親測可用)

        2.優(yōu)質(zhì)ERP系統(tǒng)帶進銷存財務(wù)生產(chǎn)功能(附源碼)

        3.優(yōu)質(zhì)SpringBoot帶工作流管理項目(附源碼)

        4.最好用的OA系統(tǒng),拿來即用(附源碼)

        5.SBoot+Vue外賣系統(tǒng)前后端都有(附源碼

        6.SBoot+Vue可視化大屏拖拽項目(附源碼)


        轉(zhuǎn)發(fā)在看就是最大的支持??

        瀏覽 30
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            伊人婷婷综合网 | (h)触手欲潮h动漫 | 亚洲情趣视频 | 小雪好紧我太爽了再快点更新时间 | free性欧美69hd | 乡村美女户外勾搭av | 亚洲成人欧美 | 亚洲一区二区三区 | 免费高清无码专区 | 国产老头老太性视频 |