电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

基于Springboot吞吐量優化解決方案

瀏覽:5日期:2023-04-21 10:02:20

一、異步執行

實現方式二種:

1.使用異步注解@aysnc、啟動類:添加@EnableAsync注解

2.JDK 8本身有一個非常好用的Future類——CompletableFuture

@AllArgsConstructorpublic 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); //告知完成結果 future.complete(60); }}

在該示例中,啟動一個線程,此時AskThread對象還沒有拿到它需要的數據,執行到 myRe = re.get() * re.get()會阻塞。我們用休眠1秒來模擬一個長時間的計算過程,并將計算結果告訴future執行結果,AskThread線程將會繼續執行。

public class Calc { public static Integer calc(Integer para) { try { //模擬一個長時間的執行 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方法構造一個CompletableFuture實例,在supplyAsync()方法中,它會在一個新線程中,執行傳入的參數。在這里它會執行calc()方法,這個方法可能是比較慢的,但這并不影響CompletableFuture實例的構造速度,supplyAsync()會立即返回。

而返回的CompletableFuture實例就可以作為這次調用的契約,在將來任何場合,用于獲得最終的計算結果。supplyAsync用于提供返回值的情況,CompletableFuture還有一個不需要返回值的異步調用方法runAsync(Runnable runnable),一般我們在優化Controller時,使用這個方法比較多。

這兩個方法如果在不指定線程池的情況下,都是在ForkJoinPool.common線程池中執行,而這個線程池中的所有線程都是Daemon(守護)線程,所以,當主線程結束時,這些線程無論執行完畢都會退出系統。

核心代碼:

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

異步調用使用Callable來實現

@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(); } /** * 異步調用restful * 當controller返回值是Callable的時候,springmvc就會啟動一個線程將Callable交給TaskExecutor去處理 * 然后DispatcherServlet還有所有的spring攔截器都退出主線程,然后把response保持打開的狀態 * 當Callable執行結束之后,springmvc就會重新啟動分配一個request請求,然后DispatcherServlet就重新 * 調用和處理Callable異步執行的返回結果, 然后返回視圖 * * @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; } }

異步調用的方式 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鐘沒返回,則認為超時 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() + ' 執行完畢'); } }); webAsyncTask.onTimeout(new Callable<String>() { @Override public String call() throws Exception { logger.info(Thread.currentThread().getName() + ' onTimeout'); // 超時的時候,直接拋異常,讓外層統一處理超時異常 throw new TimeoutException('調用超時'); } }); return webAsyncTask; } /** * 異步調用,異常處理,詳細的處理流程見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('調用超時!'); } }; logger.info(Thread.currentThread().getName() + ' 從helloController方法返回'); return new WebAsyncTask<>(20000, callable); } }

二、增加內嵌Tomcat的最大連接數

@Configurationpublic 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(); //設置最大連接數 protocol.setMaxConnections(20000); //設置最大線程數 protocol.setMaxThreads(2000); protocol.setConnectionTimeout(30000); } }}

三、使用@ComponentScan()定位掃包比@SpringBootApplication掃包更快

四、默認tomcat容器改為Undertow(Jboss下的服務器,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方式實現異步調用

@RestControllerpublic 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<>(); // 調用長時間執行任務 taskService.execute(deferredResult); // 當長時間任務中使用deferred.setResult('world');這個方法時,會從長時間任務中返回,繼續controller里面的流程 logger.info(Thread.currentThread().getName() + '從executeSlowTask方法返回'); // 超時的回調方法 deferredResult.onTimeout(new Runnable(){ @Override public void run() { logger.info(Thread.currentThread().getName() + ' onTimeout'); // 返回超時信息 deferredResult.setErrorResult('time out!'); } }); // 處理完成的回調方法,無論是超時還是處理成功,都會進入這個回調方法 deferredResult.onCompletion(new Runnable(){ @Override public void run() { logger.info(Thread.currentThread().getName() + ' onCompletion'); } }); return deferredResult; }}

七、異步調用可以使用AsyncHandlerInterceptor進行攔截

@Componentpublic 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()+ '服務調用完成,返回結果給客戶端'); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if(null != ex){ System.out.println('發生異常:'+ex.getMessage()); } } @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 攔截之后,重新寫回數據,將原來的hello world換成如下字符串 String resp = 'my name is chhliu!'; response.setContentLength(resp.length()); response.getOutputStream().write(resp.getBytes()); logger.info(Thread.currentThread().getName() + ' 進入afterConcurrentHandlingStarted方法'); } }

以上這篇基于Springboot吞吐量優化解決方案就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 好杂志网-首页| 泰国试管婴儿_泰国第三代试管婴儿_泰国试管婴儿费用/多少钱_孕泰来 | 二次元影像仪|二次元测量仪|拉力机|全自动影像测量仪厂家_苏州牧象仪器 | 医用空气消毒机-医用管路消毒机-工作服消毒柜-成都三康王 | 仓储货架_南京货架_钢制托盘_仓储笼_隔离网_环球零件盒_诺力液压车_货架-南京一品仓储设备制造公司 | 干粉砂浆设备_干混砂浆生产线_腻子粉加工设备_石膏抹灰砂浆生产成套设备厂家_干粉混合设备_砂子烘干机--郑州铭将机械设备有限公司 | 无缝方管|无缝矩形管|无缝方矩管|无锡方管厂家 | 量子管通环-自清洗过滤器-全自动反冲洗过滤器-北京罗伦过滤技术集团有限公司 | 博客-悦享汽车品质生活| 丹佛斯变频器-Danfoss战略代理经销商-上海津信变频器有限公司 | 塑料撕碎机_编织袋撕碎机_废纸撕碎机_生活垃圾撕碎机_废铁破碎机_河南鑫世昌机械制造有限公司 | 同步带轮_同步带_同步轮_iHF合发齿轮厂家-深圳市合发齿轮机械有限公司 | 智慧水务|智慧供排水利信息化|水厂软硬件系统-上海敢创 | FAG轴承,苏州FAG轴承,德国FAG轴承-恩梯必传动设备(苏州)有限公司 | 铝合金脚手架厂家-专注高空作业平台-深圳腾达安全科技 | 箱式破碎机_移动方箱式破碎机/价格/厂家_【华盛铭重工】 | 专业深孔加工_东莞深孔钻加工_东莞深孔钻_东莞深孔加工_模具深孔钻加工厂-东莞市超耀实业有限公司 | 广州昊至泉水上乐园设备有限公司 | 短信通106短信接口验证码接口群发平台_国际短信接口验证码接口群发平台-速度网络有限公司 | 山东集装箱活动房|济南集装箱活动房-济南利森集装箱有限公司 | 广东燎了网络科技有限公司官网-网站建设-珠海网络推广-高端营销型外贸网站建设-珠海专业h5建站公司「了了网」 | 涡轮流量计_LWGY智能气体液体电池供电计量表-金湖凯铭仪表有限公司 | 活性氧化铝|无烟煤滤料|活性氧化铝厂家|锰砂滤料厂家-河南新泰净水材料有限公司 | 酶联免疫分析仪-多管旋涡混合仪|混合器-莱普特科学仪器(北京)有限公司 | 无轨电动平车_轨道平车_蓄电池电动平车★尽在新乡百特智能转运设备有限公司 | 房间温控器|LonWorks|海思 | 全自动实验室洗瓶机,移液管|培养皿|进样瓶清洗机,清洗剂-广州摩特伟希尔机械设备有限责任公司 | 德州万泰装饰 - 万泰装饰装修设计软装家居馆 | 带式过滤机厂家_价格_型号规格参数-江西核威环保科技有限公司 | 不锈钢轴流风机,不锈钢电机-许昌光维防爆电机有限公司(原许昌光维特种电机技术有限公司) | 挖掘机挖斗和铲斗生产厂家选择徐州崛起机械制造有限公司 | 色油机-色母机-失重|称重式混料机-称重机-米重机-拌料机-[东莞同锐机械]精密计量科技制造商 | 爆炸冲击传感器-无线遥测传感器-航天星百科| 小型UV打印机-UV平板打印机-大型uv打印机-UV打印机源头厂家 |松普集团 | 山东钢衬塑罐_管道_反应釜厂家-淄博富邦滚塑防腐设备科技有限公司 | 净化车间装修_合肥厂房无尘室设计_合肥工厂洁净工程装修公司-安徽盛世和居装饰 | 不锈钢钢格栅板_热浸锌钢格板_镀锌钢格栅板_钢格栅盖板-格美瑞 | 空调风机,低噪声离心式通风机,不锈钢防爆风机,前倾皮带传动风机,后倾空调风机-山东捷风风机有限公司 | 上海刑事律师|刑事辩护律师|专业刑事犯罪辩护律师免费咨询-[尤辰荣]金牌上海刑事律师团队 | 奇酷教育-Python培训|UI培训|WEB大前端培训|Unity3D培训|HTML5培训|人工智能培训|JAVA开发的教育品牌 | 热闷罐-高温罐-钢渣热闷罐-山东鑫泰鑫智能热闷罐厂家 |