Detailed listener example for J2ee with high concurrency
- 2020-06-07 04:30:04
- OfStack
Detailed listener example for J2ee with high concurrency
Introduction: To limit the maximum number of concurrences at high concurrences, set parameters (maximum concurrences) with a filter in web.xml, and set other related parameters. See the code for details.
Step 1: Configure the web.xml configuration
url-pattern is the url that limits concurrency, end!
<filter>
<filter-name>ConcurrentCountFilter</filter-name>
<filter-class>com.procure.pass.ConcurrentCountFilter</filter-class>
<init-param>
<param-name>maxConcurrent</param-name>
<param-value>50</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ConcurrentCountFilter</filter-name>
<url-pattern>/a/pass/export</url-pattern>
</filter-mapping>
Step 2: Write the implementation class to implement filter, which has three methods, as shown in the code.
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Servlet Filter implementation class ConcurrentCountFilter
*/
public class ConcurrentCountFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(ConcurrentCountFilter.class);
private FilterConfig filterConfig;
private int maxConcurrent = -1;
// Total number of
private static AtomicInteger count = new AtomicInteger(0);
/**
* Gets the current concurrency value
* @return
*/
public static int get(){
return count.get();
}
/**
* Increase the number of concurrency
* @return
*/
public static int increase(){
return count.incrementAndGet();
}
/**
* Reduce the number of concurrency
* @return
*/
public static int decrement(){
return count.decrementAndGet();
}
/**
* Initialize the
*/
public void init(FilterConfig filterConfig) throws ServletException {
// Gets the maximum number of concurrent configurations
String maxStr = filterConfig.getInitParameter("maxConcurrent");
int num = -1;
if(maxStr != null && !"".equals(maxStr)){
num = Integer.parseInt(maxStr);
}
if(num >= 1){
this.maxConcurrent = num;
}else{
this.maxConcurrent = -1;
}
}
/**
* Filter master method
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try{
// Increase the number of concurrency
int num = increase();
if(maxConcurrent > 0){
if(maxConcurrent >= num){
chain.doFilter(request, response);
log.info(" The first 1 Number of secondary concurrences: "+count.get());
}else{
HttpServletResponse res = (HttpServletResponse) response;
res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE," The maximum number of concurrences is reached ");
log.info(" Reach the maximum number of concurrences ");
log.info(" Maximum number of concurrency: "+count.get());
}
}else{
chain.doFilter(request, response);
log.info(" The first 2 Number of secondary concurrences: "+count.get());
}
}finally {
decrement();
log.info(" Reduced concurrency: "+count.get());
}
}
/**
* Exit the destruction
*/
public void destroy() {
this.filterConfig = null;
log.info(" The destruction ......");
}
}
That's it for the code.
Make fun of the potholes you encountered in the project:
1. response. sendError (int string); In this code, it is res.sendError. If it is like this code directly, it will return a page from 503 server, which is very rough and ugly.
To kindly notify users, do the following steps in ES42en.xml:
<error-page>
<error-code>503</error-code>
<location>/WEB-INF/views/error/503.jsp</location>
</error-page>
If the above information is configured in web.xml, this page under the status code of 503(HttpServletResponse.SC_ES51en_ES52en) is first filtered without throwing the server's page.
The 503.ES56en page needs to be completed by yourself. Here is just one example for reference. The code is as follows:
<%
response.setStatus(503);
// Get exception class
Throwable ex = Exceptions.getThrowable(request);
if (ex != null){
LoggerFactory.getLogger("500.jsp").error(ex.getMessage(), ex);
}
// Compile error message
StringBuilder sb = new StringBuilder(" Error message: \n");
if (ex != null) {
sb.append(Exceptions.getStackTraceAsString(ex));
} else {
sb.append(" An unknown error .\n\n");
}
// If the request is asynchronous or on the phone, the message is returned
if (Servlets.isAjaxRequest(request)) {
out.print(sb);
}
// Output the exception information page
else {
%>
<%@page import="org.slf4j.Logger,org.slf4j.LoggerFactory"%>
<%@page import="com.xahl_oa.internal.common.web.Servlets"%>
<%@page import="com.xahl_oa.internal.common.utils.Exceptions"%>
<%@page import="com.xahl_oa.internal.common.utils.StringUtils"%>
<%@page contentType="text/html;charset=UTF-8" isErrorPage="true"%>
<%@include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>503 - The service is temporarily unavailable </title>
<%@include file="/WEB-INF/views/include/head.jsp" %>
</head>
<body>
<div class="container-fluid">
<div class="page-header"><h1> The service is temporarily unavailable. Please try again later .</h1></div>
<div class="errorMessage">
Error message: <%=ex==null?" An unknown error .":StringUtils.toHtml(ex.getMessage())%> <br/> <br/>
The server is temporarily unavailable, please try again later, thank you! <br/> <br/>
<a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="history.go(-1);" class="btn"> On the back 1 page </a>
<a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn"> View details </a>
</div>
<div class="errorMessage hide">
<%=StringUtils.toHtml(sb.toString())%> <br/>
<a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="history.go(-1);" class="btn"> On the back 1 page </a>
<a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn"> Hide details </a>
<br/> <br/>
</div>
<script>try{top.$.jBox.closeTip();}catch(e){}</script>
</div>
</body>
</html>
<%
} out = pageContext.pushBody();
%>
This page is much friendlier than the page thrown by the server.
Thank you for reading, I hope to help you, thank you for your support to this site!