Servlet and JSP performance adjustment

xiaoxiao2021-03-06  79

Overview

In this article, Rahul Chaudhary describes the use of PTT Performance-Tuning Techniques to enhance the performance of Servlets and JSP to enhance your J2EE application. The author assumes that the reader has the foundation of Servlets and JSPS knowledge.

Author: Rahul Chaudhary

Translator: Guipei

Is your J2EE application running slow? Can they meet enough pressure? This article will describe how to develop high-performance applications and JSPs and servlets to use performance adjustment technology (PTT Performance-Tuning Techniques). Using these technologies can construct a more fast and robust system to meet more users or more requests. In this article, I will take you practical practice. How to adjust the performance to improve your servlets and JSP pages, ultimately to enhance your J2EE application performance. One of the technologies used in the development process, that is, adapt to the system design or writing code. Others are and configure related technologies.

Adjustment method 1: Cache data using httpservlet init () method

When the application server starts constructing in the servlet, the init () method that calls the servlet before being processed. Only call only once in the life cycle of the servlet. The init () method is used to improve performance during initialization by cache static data or completing the operation of a large number of resources.

For example, it is a best practice by using a JDBC connection pool, when calling a javax.sql.datasource interface. Rely on the DataSource with the JNDI (Java Names and Service Interface) tree. If JNDI finds DataSource is performed at each SQL call, it will seriously affect the application service. The system () method of the servlet will be used to get DataSource and cach it to be used later.

Public Class ControllerServlet Extends Httpservlet

{

Private javax.sql.datasource testds = NULL;

Public Void Init (ServletConfig Config) Throws ServleTexception

{

Super.init (config);

CONTEXT CTX = NULL;

Try

{

CTX = New InitialContext ();

Testds = (javax.sql.datasource) CTX.lookup ("JDBC / TestDS");

}

Catch (Namingexception Ne)

{

Ne.PrintStackTrace ();

}

Catch (Exception E)

{

E.PrintStackTrace ();

}

}

Public javax.sql.datasource gettestds ()

{

Return Testds;

}

...

...

}

Adjustment Method 2: Prohibition of servlet and JSP automatic overload

In order to save development time, the automatic overload function is provided in the development phase servlet / JSP container, so that you don't have to restart your service after modifying servlet / JSP. However, under the production environment, it is a large number of overhead because there is no necessary reloading operation, so it has brought very much performance impact. At the same time, it is also possible to bring a variety of strange conflicts when the partial load is loaded. Therefore, the automatic load function can be achieved in J2EE's production environment.

Translator Note:

This is deeply appreciated by me.

First, under a large-scale J2EE project, in a large pressure test, there is an inexplicable error in development mode, and some request tasks fails, which is because the system conflicts caused by the load. Second, in another large-scale J2EE project actual application, suddenly a large number of users make the system that sufficient to meet the user, after the system, database, application server and so on, have not solved the problem. Finally, I have to rule out the person to solve the site, and finally the problem is actually this reason. This incident only happened the day before yesterday.

Adjustment Method 3: Control HttpSession

Many application services require a series of customer requests, which are interdependent between them. Because the HTTP protocol is stateless, the web-based application must use session technology to maintain the connection. In order to implement the application service, the Java Servlet technology provides an API that performs session management using the HTTPSession object, but while using this feature, the HttpSession object must be read and blind, and the server also bear The response system overhead. You can use the following methods to improve performance.

By default, do not create httpSessions objects in the JSP page, the JSP page will automatically create httpSessions by default. If HTTPSESSSSSSSSSITIONS is required in your JSP page, in order to save some performance, use the following page instruction to avoid automatically create HttpSessions objects.

<% @ Page session = "false"%>

Do not store large objects to httpsession: If you store large object data to httpsession, the application server has to handle the entire HttpSession in each request, which will force the use of Java's serialization operation to occupy a large number of system resources. The performance of the application service will be reduced due to the serialization of Java.

Release HTTPSESSSIONS objects at the end: Use httpsession.invalidate () methods to eliminate sessions when they don't need it.

Set the timeout value of the session: servlet has a default timeout value. If you are inside this time, you have neither removed it, and there is no use (for any service request), the servlet service will automatically destroy it. Because the recovery of memory and garbage, the greater the timeout value, the greater the performance of the server. So, the timeout value of the SESSION is minimized as much as possible.

Adjustment Method 4: Compression using GZIP

Compression is an operation of a descendant information so that you can use the smallest spatial storage. The use of Gzip (GNU ZIP) compressed content can significantly reduce the time to download the HTML file. The smaller the information content, the faster the transmission. Therefore, if the content is compressed when generating a web application, it can be transferred faster, and it is displayed on the screen of the user. Since it is not a Gzip compression function to each browser, you must simply check if the browser supports.

The following code is to demonstrate how to send compressed content:

Public void doget (httpservletRequest request, httpservletResponse response)

THROWS IOEXCEPTION, ServletException

{

OutputStream out = null

// check the accepting-encoding header from the http request.

// if the header incrudes Gzip, choose gzip.

// if the header incrudes compress, choose zip.// Otherwise choose no compression.

String Encoding = Request.getHeader ("Accept-encoding");

IF (Encoding! = Null && Encoding.indexof ("gzip")! = -1)

{

Response.setHeader ("Content-Encoding", "Gzip");

OUT = New gzipoutputstream (response.getoutputstream ());

}

Else IF (Encoding! = Null && Encoding.indexof ("compress")! = -1)

{

Response.setHeader ("Content-Encoding", "Compress");

OUT = New ZipOutputStream (response.getOutputStream ());

}

Else

{

OUT = response.getOutputStream ();

}

...

...

}

Adjustment method 5: Do not use SingleThreadModel

SingleThreadModel interface Make sure servlets only accepts a request at the same time. If the servlet implements this interface, servlet will create an isolated Servelet instance for each new request, which will cause large system overhead. If you need to handle thread security issues, you can use other methods to replace this method. The SingLethReadModel interface in servlet2.4 has been opposed.

Adjustment method 6: use thread pool

The servlet engine creates an isolated thread for each request, assigns this thread to the service () method, remove this thread after it is executed. By default, the servlet engine creates new threads for each request. This behavior will cause performance issues because it is required to create and eliminate threads. Performance can be improved by using a thread pool. Configure the maximum, minimum, and increased number of thread pools based on the number of concurrent users desired. When the service is started, the servlet engine creates a thread pool using the minimum number of threads. Then the servlet engine assigns the thread to each request, replacing the original creation of the new thread, returns the thread to the thread pool after the processing is complete. With thread pools, performance will have a significant increase. If necessary, depending on the maximum and number of threads, more threads are created, added to the pool for more requests.

Adjustment method 7: Select the correct included mechanism

There are two ways in JSP to use the included file: including instructions (<% @ include file = "test.jsp"%>) and include action ( ). Contains instructions to include file content during conversion; that is, when a page is converted into a servlet. The action contains the file content in the request processing; that is, when a user requests the page. The instruction of the instruction is faster than the actions. Therefore, unless the content being included is often changed, it should be used to include instruction lifting performance.

Adjustment method 8: Select the correct range in use using usebean action

One powerful feature of the JSP page is to interact with JavaBeans components in JSP. By using the Action tab, JavaBeans can be directly embedded in the JSP page. The syntax is as follows:

"package.classname" type = "typeename">

The range attribute specifies the scope of the bean. Its default is Page. You can choose the correct range based on your system requirements. Otherwise it will affect the performance of the application system.

For example, if you need an object to use as a request, but your range is set to session. After you complete the request, this object will remain in memory. Until you clearly clear it, by destroying Session, or session automatically timeout. If you don't choose the right range, it also affects performance because of over-memory and garbage collection. Therefore, it is necessary to set the range of objects in the same way, and when you are done, you should immediately remove them.

Other methods:

Avoid string plus: Use operations will generate a lot of temporary objects because String is an immutable object. The more operations, the more temporary objects will be created, resulting in large system overhead. Use StringBuffer to replace operation when you need a string to add.

Avoid using system.out.println: system.out.println is synchronized in the Disk I / O operation and will seriously affect performance. Therefore, the most likely avoiding using System.out.Println. Although there is a powerful debugging tool, sometimes in order to track the purpose, error handling, debugging procedures, or using System.out.Println. You should configure system.out.println to use only in development and commissioning. Using a static Final Boolean variable, in production mode, configure it into false to avoid the use of System.out.Println.

ServletOutputStream Comparison PrintWriter: Use PrintWriter to occupy some system overhead because it is the output output function of the character stream. So PrintWriter should be used in environments that ensure character set conversion. In other words, when you know that servlet returns just binary data, you should use servletOutputStream so you can eliminate character conversion overhead, when the servlet container does not have to handle character sets.

to sum up

The purpose of this paper is to enhance the performance of the J2EE application by boosting the performance of the Servlets and JSP pages through some practical operations. The next time, performance adjustments will be involved in EJB (Enterprise Javabeans, JMS (Java Message Service), And Java Database Connectivity.

转载请注明原文地址:https://www.9cbs.com/read-107709.html

New Post(0)