当前位置:网站首页>Servlet3 0 + event driven for high performance long polling
Servlet3 0 + event driven for high performance long polling
2022-04-23 05:06:00 【hi wei】
servlet3.0 Asynchronous principle of
servlet I won't introduce the basics , Here is the introduction servlet3.0 An important new feature of : asynchronous .
servlet3.0 Schematic diagram :
- tomcat After receiving the request from the client, the request will be AsyncContext To the business thread , such tomcat The worker thread can release the connection to handle other requests .
- The business thread pool received AsyncContext after , You can handle the request business , After completing the business logic , according to AsyncContext obtain response, Return the response result .
- AsyncListener Will listen AsyncContext act , We can make corresponding business processing according to specific behavior .
servlet3.0 take tomcat Separate worker threads from business threads , such tomcat Worker threads can handle more connection requests . Business threads mainly deal with business logic . In this mode , The number of business threads can be better allocated , Also according to different business , Set a different number of threads , More flexible .
Be careful :tomcat Of NIO and servlet3.0 Asynchrony doesn't matter .tomcat NIO Pattern , Is for http Connection processing uses , The goal is to handle more connections with fewer threads .servlet3.0 Is in tomcat The processing logic of the working thread realizes the asynchronous processing function .
Use servlet3.0 Implement long polling
- What is long polling :
Long polling means that the client will always send requests to the server , It is applicable to the use of pushing data from the server to the client . Long polling should meet the following points :
- After the client initiates the request , When there is no data on the service side , Will not immediately return a null value , It is hold Live connection , Wait for data generation and return immediately .
- The request has a timeout on the server , Not all the time hold live . When the timeout after , The server will return timeout information , After receiving the return, the client will initiate the request again .
- After each request , The client will initiate the request again .
- Short polling 、 Long polling and long connection comparison :
- Short polling : The client sends to the server regularly Ajax request , After receiving the request, the server immediately returns the response information and closes the connection .
advantage : Back end programming is easier , Suitable for small applications ..
shortcoming : Most of the requests are useless , Waste bandwidth and server resources .
example : - Long polling : The client sends to the server Ajax request , The server receives the request hold Live connection , The response information is not returned and the connection is closed until there is a new message , After the client processes the response information, it sends a new request to the server .
advantage : Not frequent requests without messages .
shortcoming : The server hold Connections consume resources . - A long connection : The client and the server establish a long connection socket
advantage : High reliability , Real time high .
shortcoming : The implementation is complex , To maintain the heartbeat , The server maintains the connection and consumes resources .
Long polling implementation
Schematic diagram :
- After the request came in, , Generate an event , Add the corresponding event set . The request is set 30s Timeout time , And add monitor .tomcat Worker thread release .
- When the server data is ready , Trigger the corresponding event , Get subscription events from the container for execution . return when done response.
- request timeout ,listener Trigger , Return timeout information .
Let's see the specific implementation :
- Event definition , Here is just a simple event :
package com.hiwe.demo.event;
import javax.servlet.AsyncContext;
public class HttpEvent {
/** * It can be a business data primary key , Use the request name here as a simple demo */
private String requestName;
private AsyncContext asyncContext;
public HttpEvent(String requestName,AsyncContext asyncContext){
this.requestName = requestName;
this.asyncContext = asyncContext;
}
public String getRequestName() {
return requestName;
}
public AsyncContext getAsyncContext() {
return asyncContext;
}
}
Event manager :
package com.hiwe.demo.event;
import javax.servlet.AsyncContext;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class EventManager {
private final static Map<String,HttpEvent> subHttpEvents = new HashMap<>();
/** * New event subscription * @param event */
public static void addHttpEvent(HttpEvent event){
subHttpEvents.put(event.getRequestName(),event);
}
/** * Triggering event * @param requestName */
public static void onEvent(String requestName){
HttpEvent httpEvent = subHttpEvents.get(requestName);
if(httpEvent==null){
return;
}
AsyncContext asyncContext = httpEvent.getAsyncContext();
try {
PrintWriter writer = asyncContext.getResponse().getWriter();
writer.print(requestName+" request success!");
writer.flush();
asyncContext.complete();
subHttpEvents.remove(requestName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Asynchronous request listener :
package com.hiwe.demo.listener;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.PrintWriter;
@WebListener
public class AppAsyncListener implements AsyncListener {
@Override
public void onComplete(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onComplete");
// we can do resource cleanup activity here
}
@Override
public void onError(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onError");
//we can return error response to client
}
@Override
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onStartAsync");
//we can log the event here
}
/** * Timeout trigger * @param asyncEvent * @throws IOException */
@Override
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
AsyncContext asyncContext = asyncEvent.getAsyncContext();
ServletResponse response = asyncEvent.getAsyncContext().getResponse();
PrintWriter out = response.getWriter();
// return code code , So that the front end can identify , And rebuild the request
out.write(201+" longPolling timeout");
out.flush();
asyncContext.complete();
}
}
- Long polling interface :
package com.hiwe.demo.controller;
import com.hiwe.demo.listener.AppAsyncListener;
import com.hiwe.demo.event.EventManager;
import com.hiwe.demo.event.HttpEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/app")
public class AsyncController {
/** * Long polling interface * @param requestName * @param request * @param response */
@GetMapping("/asyncGet")
public void getDemo(@RequestParam(value = "requestName") String requestName, HttpServletRequest request, HttpServletResponse response){
// Turn on Asynchronous Support
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
AsyncContext asyncContext = request.startAsync();
// Add listener
asyncContext.addListener(new AppAsyncListener());
// Set timeout
asyncContext.setTimeout(30000);
// Add to the event collection
HttpEvent httpEvent = new HttpEvent(requestName, asyncContext);
EventManager.addHttpEvent(httpEvent);
}
/** * Trigger events use * @param requestName */
@GetMapping("/trigger")
public void triggerDemo(@RequestParam(value = "requestName") String requestName){
EventManager.onEvent(requestName);
}
}
The above simple long polling is realized , We can test :
After starting the application, access :http://localhost:8080/app/asyncGet?requestName=123
The server is not ready because the data is not ready , So will hold Request for accommodation . When waiting 30s The timeout information will be returned after :
We are 30s Internal trigger event:http://localhost:8080/app/trigger?requestName=123
return :
The whole long polling implementation above is completed , If there is an error , Welcome to correct !
版权声明
本文为[hi wei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220550379278.html
边栏推荐
- 洛谷P2731骑马修栅栏
- Innovation training (VI) routing
- C. Tree Infection(模拟+贪心)
- Innovation training (VII) FBV view & CBV view
- 信息学奥赛一本通 1955:【11NOIP普及组】瑞士轮 | OpenJudge 4.1 4363:瑞士轮 | 洛谷 P1309 [NOIP2011 普及组] 瑞士轮
- The WebService interface writes and publishes calls to the WebService interface (I)
- Learning Android V from scratch - UI
- Innovation training (10)
- Detailed explanation of hregionserver
- L2-011 play binary tree (build tree + BFS)
猜你喜欢
2022/4/22
Use the built-in function of win to transfer files between two computers in the same LAN (the speed is the same as that between local disks)
Field injection is not recommended using @ Autowired
How can continuous integration (CI) / continuous delivery (CD) revolutionize automated testing
Basic theory of Flink
MySQL 慢查询
#define 定义常量和宏,指针和结构体
The 2021 more reading report was released, and the book consumption potential of post-95 and Post-00 rose
MySQL memo (for your own query)
What are the redis data types
随机推荐
vscode ipynb文件没有代码高亮和代码补全解决方法
A trinomial expression that causes a null pointer
configmap
[database] MySQL multi table query (I)
Wine (COM) - basic concept
scp命令详解
Learning Android V from scratch - UI
Innovation training (VI) routing
QPushbutton 槽函数被多次触发
js 判断数字字符串中是否含有字符
What are instruction cycles, machine cycles, and clock cycles?
JS engine loop mechanism: synchronous, asynchronous, event loop
Golang select priority execution
[winui3] write an imitation Explorer file manager
Independent station operation | Facebook marketing artifact - chat robot manychat
Summary of R & D technology
Barcode generation and decoding, QR code generation and decoding
深度学习笔记 —— 微调
Installing kuberneters using kubedm
Streamexecutionenvironment of Flink source code