English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spiegazione dettagliata degli listener in J2ee in situazioni di alta concorrenza

Spiegazione dettagliata degli listener in J2ee in situazioni di alta concorrenza

Introduzione: Limitare il numero massimo di connessioni concorrenti in condizioni di alta concorrenza, impostare i parametri del filtro (numero massimo di connessioni concorrenti) nel web.xml e impostare altri parametri correlati. Dettagli nel codice.
Passo 1: Configurazione di web.xml, spiegazione dei punti non chiari: il parametro 50 viene utilizzato tramite il nome del parametro maxConcurrent nel tipo di implementazione del filtro, filter-class è la classe di implementazione scritta,

url-pattern è il limite di tempo della url di limitazione della concorrenza, fine!

<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> 

Secondo passo: scrivere la classe di implementazione del filtro, che ha tre metodi, dettagliati nel codice.

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; 
/** 
 * Implementazione della classe di filtro Servlet ConcurrentCountFilter 
 */ 
public class ConcurrentCountFilter implements Filter { 
  private static Logger log = LoggerFactory.getLogger(ConcurrentCountFilter.class); 
  private FilterConfig filterConfig; 
  private int maxConcurrent = -1; 
  // Contatore totale 
  private static AtomicInteger count = new AtomicInteger(0); 
  /** 
   * Ottenere il numero di concomitanze attuale 
   * @return 
   */ 
  public static int get(){  
      return count.get();  
    }  
  /** 
   * Aumentare il numero di concomitanze 
   * @return 
   */ 
   public static int increase(){  
      return count.incrementAndGet();  
    } 
   /** 
   * Decrease concurrent count 
   * @return 
   */ 
   public static int decrement(){ 
     return count.decrementAndGet(); 
   } 
  /** 
   * Initialization 
   */ 
    public void init(FilterConfig filterConfig) throws ServletException { 
      //Get the maximum concurrent count from configuration 
      String maxStr = filterConfig.getInitParameter("maxConcurrent"); 
      int num = -1; 
      if(maxStr != null && !"".equals(maxStr)){ 
        num = Integer.parseInt(maxStr); 
      } 
      if(num >= 1){ 
        this.maxConcurrent = num; 
      } 
        this.maxConcurrent = -1; 
      } 
    } 
    /** 
     * Main filter method 
     */ 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
      try{ 
      //Increase concurrent count 
      int num = increase(); 
      if(maxConcurrent > 0){ 
        if(maxConcurrent >= num){ 
          chain.doFilter(request, response); 
          log.info("First concurrent count: " + count.get()); 
        } 
          HttpServletResponse res = (HttpServletResponse) response; 
          res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Reached maximum concurrent limit"); 
          log.info("Reached maximum concurrent number"); 
          log.info("Maximum concurrent count: " + count.get()); 
        } 
      } 
        chain.doFilter(request, response); 
        log.info("Second concurrent count: " + count.get()); 
      } 
      } 
        decrement(); 
        log.info("Decreased concurrency: " + count.get()); 
      } 
    } 
  /** 
   /* Exit destruction 
   */ 
  public void destroy() { 
    this.filterConfig = null; 
    log.info("Destroying......"); 
  } 
} 

The code is completed here.

Complain about the pitfalls encountered in the project:

1.response.sendError(int, string); In the code of this article, it is res.sendError. If it is used directly as in the code of this article, it will return a 503 server page that is rough and ugly.

To notify users in a friendly manner, the following steps need to be taken, the following configuration code needs to be made in web.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, the page under the 503 (HttpServletResponse.SC_SERVICE_UNAVAILABLE) status code will be filtered first and the server page will not be thrown.

The 503.jsp page needs to be completed by yourself. Here is just a reference example, the code is as follows:

<% 
response.setStatus(503); 
// Get the exception class 
Throwable ex = Exceptions.getThrowable(request); 
if (ex != null){ 
  LoggerFactory.getLogger("500.jsp").error(ex.getMessage(), ex); 
} 
// Compile error information 
StringBuilder sb = new StringBuilder("Error information:\n"); 
if (ex != null) { 
  sb.append(Exceptions.getStackTraceAsString(ex)); 
} 
  sb.append("Unknown error.\n\n"); 
} 
// If it is an asynchronous request or a mobile device, return the information directly 
if (Servlets.isAjaxRequest(request)) { 
  out.print(sb); 
} 
// Output abnormal 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 - Il servizio è temporaneamente non disponibile</title> 
  <%@include file="/WEB-INF/views/include/head.jsp" %> 
</head> 
<body> 
  <div class="container-fluid"> 
    <div class="page-header"><h1>Il servizio è temporaneamente non disponibile, per favore riprova più tardi.</h1></div> 
    <div class="errorMessage"> 
      Messaggio di errore: <%=ex==null?"Errore sconosciuto.":StringUtils.toHtml(ex.getMessage())%> <br/> <br/> 
      Il server è temporaneamente non disponibile, per favore riprova più tardi. Grazie!<br/> <br/> 
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="history.go(-1);" class="btn">Torna alla pagina precedente</a>  
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn">Visualizza dettagli</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">Torna alla pagina precedente</a>  
      <a href="javascript:" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('.errorMessage').toggle();" class="btn">Nascondi i dettagli</a> 
      <br/> <br/> 
    </div> 
    <script>try{top.$.jBox.closeTip();}catch(e){}</script> 
  </div> 
</body> 
</html> 
<% 
out = pageContext.pushBody(); 
%> 

Questa pagina è molto più amichevole rispetto alla pagina generata dal server.

Grazie per la lettura, speriamo che possa aiutare tutti, grazie per il supporto di questo sito!

Dichiarazione: il contenuto di questo articolo è stato prelevato da Internet, il copyright è dell'autore originale, il contenuto è stato contribuito e caricato autonomamente dagli utenti di Internet, questo sito non detiene i diritti di proprietà, non è stato editato manualmente e non assume alcuna responsabilità legale. Se trovi contenuti sospetti di violazione del copyright, ti preghiamo di inviare una e-mail a: notice#oldtoolbag.com (al momento dell'invio dell'e-mail, sostituisci # con @) per segnalare il problema e fornire prove pertinenti. Una volta verificata, questo sito eliminerà immediatamente i contenuti sospetti di violazione del copyright.

Ti potrebbe interessare