日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
SpringBoot性能太差?試試這幾招!

今天這篇文章介紹七種常見的Spring Boot 性能優(yōu)化方向。

目前成都創(chuàng)新互聯(lián)公司已為1000+的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站運營、企業(yè)網(wǎng)站設(shè)計、朝陽網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

1. 異步執(zhí)行

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

  • 使用異步注解@Aysnc?、啟動類:添加@EnableAsync 注解。
  • JDK 8 本身有一個非常好用的 Future 類——CompletableFuture。
@AllArgsConstructor  
public class AskThread implements Runnable{
private CompletableFuture 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 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í)行。

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 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é)果。

supplyAsync? 用于提供返回值的情況,CompletableFuture? 還有一個不需要返回值的異步調(diào)用方法 runAsync(Runnable runnable)?,一般我們在優(yōu)化 Controller 時,使用這個方法比較多。

這兩個方法如果在不指定線程池的情況下,都是在 ForkJoinPool.common 線程池中執(zhí)行,而這個線程池中的所有線程都是 Daemon(守護)線程,所以,當主線程結(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
* 當controller返回值是Callable的時候,springmvc就會啟動一個線程將Callable交給TaskExecutor去處理
* 然后DispatcherServlet還有所有的spring攔截器都退出主線程,然后把response保持打開的狀態(tài)
* 當Callable執(zhí)行結(jié)束之后,springmvc就會重新啟動分配一個request請求,然后DispatcherServlet就重新
* 調(diào)用和處理Callable異步執(zhí)行的返回結(jié)果, 然后返回視圖
*
* @return
*/
@GetMapping("/hello")
public Callable helloController() {
logger.info(Thread.currentThread().getName() + " 進入helloController方法");
Callable callable = new Callable() {

@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 worldController() {
logger.info(Thread.currentThread().getName() + " 進入helloController方法");

// 3s鐘沒返回,則認為超時
WebAsyncTask webAsyncTask = new WebAsyncTask<>(3000, new Callable() {

@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() {

@Override
public String call() throws Exception {
logger.info(Thread.currentThread().getName() + " onTimeout");
// 超時的時候,直接拋異常,讓外層統(tǒng)一處理超時異常
throw new TimeoutException("調(diào)用超時");
}
});
return webAsyncTask;
}

/**
* 異步調(diào)用,異常處理,詳細的處理流程見MyExceptionHandler類
*
* @return
*/
@GetMapping("/exception")
public WebAsyncTask exceptionController() {
logger.info(Thread.currentThread().getName() + " 進入helloController方法");
Callable callable = new Callable() {

@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);
}

}

2. 增加內(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);
}
}

}

3. 使用 @ComponentScan()

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

4. 默認 Tomcat 容器改為 Undertow

默認 Tomcat 容器改為 Undertow(Jboss 下的服務(wù)器,Tomcat 吞吐量 5000,Undertow 吞吐量 8000)

  

org.springframework.boot
spring-boot-starter-tomcat

改為:

  
org.springframework.boot
spring-boot-starter-undertow

5. 使用 BufferedWriter 進行緩沖

這里不給大家舉例,可自行嘗試。

6. 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 executeSlowTask() {
logger.info(Thread.currentThread().getName() + "進入executeSlowTask方法");
DeferredResult deferredResult = new DeferredResult<>();
// 調(diào)用長時間執(zhí)行任務(wù)
taskService.execute(deferredResult);
// 當長時間任務(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;
}
}

7. 異步調(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方法");
}

}


本文題目:SpringBoot性能太差?試試這幾招!
鏈接地址:http://m.5511xx.com/article/cciedgp.html