服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - J2ee 高并发情况下监听器实例详解

J2ee 高并发情况下监听器实例详解

2020-08-12 13:59Smy_0114 Java教程

这篇文章主要介绍了J2ee 高并发情况下监听器实例详解的相关资料,需要的朋友可以参考下

J2ee 高并发情况下监听器实例详解

引言:在高并发下限制最大并发次数,在web.xml中用过滤器设置参数(最大并发数),并设置其他相关参数。详细见代码。
第一步:配置web.xml配置,不懂的地方解释一下:参数50通过参数名maxConcurrent用在filter的实现类中获取,filter-class就是写的实现类,

url-pattern就是限制并发时间的url,结束!

?
1
2
3
4
5
6
7
8
9
10
11
12
<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>

第二步:写实现类实现filter,该接口有三个方法,详见代码。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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;
  //总计数
  private static AtomicInteger count = new AtomicInteger(0);
   
  /**
   * 获取当前并发数
   * @return
   */
  public static int get(){ 
      return count.get(); 
    
  /**
   * 增加并发数量
   * @return
   */
   public static int increase(){ 
      return count.incrementAndGet(); 
    }
   /**
   * 减少并发数量
   * @return
   */
   public static int decrement(){
     return count.decrementAndGet();
   }
   
    
  /**
   * 初始化
   */
    public void init(FilterConfig filterConfig) throws ServletException {
      //获取配置的最大并发数量
      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;
      }
    }
    /**
     * 过滤主方法
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      try{
      //增加并发数量
      int num = increase();
      if(maxConcurrent > 0){
        if(maxConcurrent >= num){
          chain.doFilter(request, response);
          log.info("第一次并发数量:"+count.get());
        }else{
          HttpServletResponse res = (HttpServletResponse) response;
          res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,"达到最大并发数限制");
          log.info("达到最大并发数");
          log.info("最大并发数量:"+count.get());
        }
      }else{
        chain.doFilter(request, response);
        log.info("第二次并发数量:"+count.get());
      }
      }finally {
        decrement();
        log.info("减小的并发量:"+count.get());
      }
     
    }
  /**
   * 退出销毁
   */
  public void destroy() {
    this.filterConfig = null;
    log.info("销毁......");
  }
}

代码到此完。

吐槽一下自己在项目中遇到的坑:

1.response.sendError( int, string);在本文代码中为res.sendError其中若直接如本文代码那样会返回一个503服务器带出来的页面,此页面粗暴及其难看,

在此为了友好通知用户,需做如下步骤,在web.xml中做如下配置代码:

?
1
2
3
4
<error-page>
  <error-code>503</error-code>
  <location>/WEB-INF/views/error/503.jsp</location>
 </error-page>

如果在web.xml中配置了上面信息,首先会过滤503(HttpServletResponse.SC_SERVICE_UNAVAILABLE)状态码下的此页面而不会抛服务器的页面。

其中503.jsp页面需自己完成在此仅仅贴出来一个示例做参考,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<%
response.setStatus(503);
 
// 获取异常类
Throwable ex = Exceptions.getThrowable(request);
if (ex != null){
  LoggerFactory.getLogger("500.jsp").error(ex.getMessage(), ex);
}
 
// 编译错误信息
StringBuilder sb = new StringBuilder("错误信息:\n");
if (ex != null) {
  sb.append(Exceptions.getStackTraceAsString(ex));
} else {
  sb.append("未知错误.\n\n");
}
 
// 如果是异步请求或是手机端,则直接返回信息
if (Servlets.isAjaxRequest(request)) {
  out.print(sb);
}
 
// 输出异常信息页面
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 - 服务暂时不可用</title>
  <%@include file="/WEB-INF/views/include/head.jsp" %>
</head>
<body>
  <div class="container-fluid">
    <div class="page-header"><h1>服务暂时不可用请稍后再试.</h1></div>
    <div class="errorMessage">
      错误信息:<%=ex==null?"未知错误.":StringUtils.toHtml(ex.getMessage())%> <br/> <br/>
      服务器暂时不可用请稍后再试,谢谢!<br/> <br/>
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="history.go(-1);" class="btn">返回上一页</a> 
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn">查看详细信息</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">返回上一页</a> 
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn">隐藏详细信息</a>
      <br/> <br/>
    </div>
    <script>try{top.$.jBox.closeTip();}catch(e){}</script>
  </div>
</body>
</html>
<%
} out = pageContext.pushBody();
%>

此页面就比服务器抛出的页面友好甚多。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/smy_0114/article/details/55270707

延伸 · 阅读

精彩推荐