How to Improve Java Web service performance by using the jie instance

Source: Internet
Author: User

This article introduces how to improve Java Web service performance. It mainly introduces three methods: one is asynchronous calling of Web Services, the other is introducing the Web Service batch processing mode, and the other is compressing SOAP messages. This section focuses on how to use Asynchronous Web Services and differences between asynchronous and synchronous calls during programming. This article also demonstrates how to use the above three methods in the project and the applicable scenarios of various methods.

Java Web Services

Web services are a service-oriented architecture technology that provides services through standard Web protocols. The purpose is to ensure the interoperability of application services on different platforms. Web Service is a Service based on XML and HTTP Communication. Its communication protocol is mainly based on SOAP. The Service description uses WSDL and UDDI to discover and obtain Service metadata. This Web Service, based on XML standards and Internet protocols, is the next development direction of distributed computing, web services bring bright prospects for communications and collaboration between commercial applications built on different resources, so that they can collaborate with each other without the impact of their underlying implementation solutions.

JAX-RPC 1.0 is the original standard of Web Services in Java, but because JAX-RPC 1.0 has some limitations on Web service functions, so the application of JAX-WS 2.0 was born. The main goal of JAX-WS 2.0 development is to update various standards and successfully fulfill the industry's expectations for JAX-RPC 1.X. In addition, JAX-WS 2.0 directly supports XOP/MTOM, improving the attachment transfer capability and interoperability between systems.

Instance profiling Web service performance bottlenecks

Through the above description, it is not difficult to understand that Web services will become the foundation of data sharing in the future by integrating XML + HTTP with loose coupling and platform-independent features. But at the same time, we should also realize that everything in the world has its two sides of conflict: advantages, disadvantages, and Web services. Just like when JAVA became popular, its performance became a fatal criticism, Web Services also faced performance problems. It seems that "performance problems" are inherently "platform-independent. But the problem should be solved at the end. practice is the only way to test and analyze the problem. Let's create a simple Web service to review and analyze the hidden performance problems.

Create a service

Create a service Java Bean: first, create a simple bookstore service Bean. The service content only has one qryBooksByAuthor, that is, query the List of books under the Author (Author ).

Figure 1. BookStoreSrvBean)

Service Input-Author (Author) entity class:

Figure 2. Author object class (Author)

Entity classes in the Output-Book list of service Output parameters:

Figure 3. Book)

So far, our service code has been completed. We do not discuss the rationality of the service here. The purpose of creating this service is to give an instance as simple as possible to analyze the performance of the web service.

The following task is to develop Web services. It is extremely cumbersome to manually write and release compliant Web Services. Here we use IBM's Rational Software Architect (RSA) to develop the Web service server and client.

Publish Web Services

Create a Dynamic Web Project: a J2EE Web Project is required to publish Web Services. Open RSA> File> New> Dynamic Web Project. The Project name is testWebService, select other options as needed (note that you need to add the Web Project to the EAR ). The effect of the created Web project and EAR project is as follows:

Figure 4. Structure of Web Project and Application Project

Create Web Service: select the imported com. ibm. test. ws. srv. BookStoreSrvBean, right-click New-> Other-> Web Service to create and publish the Web Service. Select common JAX-WS standards when creating and select generate a wsdl file. The creation of Web services is not the focus of this article. After the service is created, it can be published to the Web project created in the previous step.

Create a client

Using RSA, the creation of the Client is very simple: Right-click the generated WSDL File above-> Web Services-> Generate Client

Figure 5. Create a client

On this page, select the target project for the server, JAX-WS standard, and Client code based on the actual situation, and then click Next.

Figure 6. Enter client information

This interface uses the default configuration for the time being. Some special options will be described later.

Client call

Since most of the stub call code in the JAX-WS specification is generated in real time, we only need to modify the port of the client WSDL to call the Web service with the following code. Here, the purpose of modifying the WSDL port is to allow the client to call the virtual port of the TCP/IP Monitor provided by RSA, so that we can easily see the actual call of the Web service and the returned SOAP message.

The client call code is as follows:

Figure 7. Client call code

The SOAP message displayed by using TCP/IP Monitor is as follows:

Figure 8. SOAP messages generated by Web service calls

Java Web Service Performance Analysis

From the above examples, we can see that the call of Web Services is quite different from the traditional RPC. The biggest feature is that the caller uses the SOAP standard message in XML format for transmission. The advantage of text transmission is that the private protocol is abandoned, regardless of the platform on which the caller is called, as long as the XML text can be constructed and parsed and there is a transfer protocol supported by both parties, the call becomes possible. The increasingly standardized XML and the popularity of HTTP Protocol provide strong support for these two conditions. It is an indisputable fact that Web services will become a standard for general services in the future.

However, I believe that all people who have used Web services have suffered from poor performance. The reason is that we can analyze the following points based on the previous example:

● Low efficiency caused by conversion of SOAP text messages

We can see from the request and response messages detected by TCP/IP Monitor, we passed in the Author object when sending the message. When the actual call occurs, this Author object will be converted into a SOAP message in XML format. When the message arrives at the Server side, it will be parsed and re-constructed into an Author object on the Server side. The same is true for Response. Books List also goes through XML serialization and deserialization. Worst of all, this process will occur during every call. This construction and resolution process will consume a lot of CPU, resulting in resource consumption.

● Transmission of SOAP text messages leads to expansion of transmission content

Taking the request parameter Author as an example, the necessary information is only the "Bruce Eckel" bytes, but after being converted into an XML message, we can see from the SOAP message that there are a lot more SOAP standard labels, this information will cause a sharp increase in the amount of content to be transmitted, and several bytes may become several thousand bytes. When the call frequency and parameter content increase, the expansion of the transmission content will not be negligible, it will not only eat the bandwidth of the network, it will also burden the Server's data throughput capacity, and the consequences can be imagined.

● Synchronous blocking calls may cause low performance in some cases

Synchronous blocking call means that the client is always in the blocking state after the Web Service is called to send a request, and the client thread will be suspended and remain in the waiting state. Other tasks cannot be processed. This will cause thread waste. If the corresponding thread occupies some resources, it cannot be released in time.

This problem is not obvious when the client accesses the Server. However, if the Web service is called between two servers, blocking mode will become a performance bottleneck for the Server.

Web Service Performance Optimization practices

Call web Services Asynchronously

It should be emphasized that the Asynchronous Method here refers to the client's Asynchronization. Whether the client is synchronous or asynchronous, it has no impact on the server. The expected result is that after the client sends a call request, it does not have to block the request and wait for the server to return the result. The latest JAX-WS standard adds the feature of this asynchronous call, better news is that the RSA tool also supports this feature of the JAX-WS, this greatly facilitates the creation of asynchronous call clients.

In fact, it is extremely simple to configure the Client as an asynchronous mode. You only need to select 'Enable asynchronous invocation for generated client' when RSA generates the client code. for example:

Figure 9. Options for creating an asynchronous Client

In this way, qryBooksByAuthorAsync asynchronous methods will be added to the generated client's BookStoreSrvBeanService. Since it is an Asynchronous Method, callback is essential. In the following asynchronous client test code, you can see the specific usage of anonymous internal classes as Callback handler:

Figure 10. Sample Code of asynchronous client call

The output result of the test code is as follows:

Figure 11. asynchronous call console output

As you can see, when the Web service does not return, the client still has the opportunity to make its own output: "not done yet, can do something else ...". Some may think that the output as a client is meaningless, but if a server accesses a Web service as a client, if you have the opportunity to execute the code you need out of the blocking status during service waiting, you can even use wait or other methods to release the resources occupied by the current thread, for this server, this will be an essential factor for performance improvement.

Enable the web service to support the batch processing mode

● Batch processing mode Overview

Batch Processing, as its name implies, replaces the traditional processing method of one transaction by processing multiple transactions at a time. Java Database Connectivty (JDBC) provides a large number of batch processing APIs to optimize Database operation performance. For example, Statement.exe cuteBatch () can receive and execute multiple SQL statements at a time. The batch processing idea can be easily transplanted to the Web service call scenario to optimize the Web service call response. The actual Web service call timestamp analysis shows that network communication is one of the bottlenecks of Web service performance. Therefore, the Web service performance is optimized by reducing network communication overhead, the batch processing mode is a direct implementation method.

● Batch processing mode Adaptability

Although the batch processing mode plays a significant role, it is not suitable for all scenarios. When using the batch processing mode to process Web Service requests, consider the following:

1. Different Web Service execution time differences

Different Web services have different execution times. Therefore, this time difference must be considered when processing multiple Web Service requests simultaneously. Generally, after the Web service with the longest processing time is executed, the execution results of all Web services are summarized and returned to the client, therefore, multiple Web Services in batch processing consume a longer time than a single sequential invocation of Web Services. You need to have a clear understanding of Web Services before using the batch processing mode, and try to include Web services with similar performance parameters into batch processing as much as possible, while processing Web services with a large difference in execution time. It is generally recommended that multiple Web services with a performance difference of less than 30% be considered for batch processing. For example, in AccountWebService, there is a Web Service getUserAccounts that obtains the user account list. It takes 15 seconds to execute this Web Service, and in UserWebService, there is a getuserpendingconfigurations that gets the user's pending notifications, the execution of this Web Service takes 2 seconds. We can see that the execution time of these two Web Services is significantly different. Therefore, we do not recommend that you include these two Web Services in batch processing. In AccountWebService, there is a Web Service addThirdPartyNonHostAccount that adds a third-party user account. It takes 3 seconds for the Web service to be executed, in this case, you can consider placing the getuserpendingconfigurations Web service and addThirdPartyNonHostAccount in a batch for one-time call processing.

2. Business relevance of different Web Services

Generally, we recommend that you add multiple Web services with business relevance to batch processing. Only multi-Web services with business relevance can reduce the number of calls to improve application system performance. For example, after a user adds a third-party account addThirdPartyNonHostAccount, a pending notification is automatically sent to the user by default, prompting the user to activate the added account, therefore, in this scenario, the addThirdPartyNonHostAccount Web Service and the getuserpendingconfigurations Web service can be perfectly put into a batch. After the user adds a third-party account, the system automatically refreshes the pending notification area to notify the user to activate the account. UserWebService has a Web Service getUserHostAccounts for obtaining the user's primary account and getUserNonHostAccounts for obtaining the user's third-party account. MetaDataService has a Web Service getFinacialAgencyHolidays for obtaining the holiday data of national financial institutions, this Web Service obviously has no business relevance with getUserHostAccounts and getUserNonHostAccounts, so they should not be included in batch processing.

3. Try to avoid putting dependency-related Web services in the same batch.

Putting multiple dependency-related Web services into the same batch of processing requires special consideration and processing of the dependencies between multiple Web services, in this way, you cannot concurrently execute convenient Web Services and have to execute dependency-Related Web Services in serial mode, in the most pessimistic case, the batch processing response time will be the serial execution time and of all Web Services in the batch processing. In principle, even if there is a dependency between Web Services in batch processing, multiple Web services can be called through batch processing by dynamically specifying the dependency. However, this will greatly increase the technical complexity of batch processing, so we do not recommend this operation.

4. multi-threaded processing of Web Service requests in batch

The batch processing mode generally processes multiple Web service call requests concurrently through multi-thread processing on the service implementation end. A centralized parser is used to parse requests in the batch processing mode. Then, a separate thread is started for each Web service call to process this Web request, at the same time, there will be a general thread manager to schedule different Web Service Execution threads and monitor the thread execution progress. After All threads are executed, the Web Service execution result is summarized and returned to the client.

● Batch processing Implementation Method

There are two Batch Processing Methods: static batch processing mode and dynamic batch processing mode:

The static batch processing mode is relatively simple, but lacks flexibility. The core idea of static batch processing is to obtain batch processing through combined encapsulation based on existing Web Services. For example, the existing Web service request structure in the system is combined into a new data object model as the Web Service Batch Processing request structure, when the client performs a batch processing call, it initializes the Batch Processing request data object and assigns a specific Web service request object to the Batch Processing request object attribute. Similarly, when the service implementation end processes Response Data Objects in batches, it also combines the response of a specific Web service to generate and return the response to the client.

The implementation of the dynamic batch processing mode is complex, but it also provides greater operation flexibility. The dynamic batch processing mode generally requires applications to use Java reflection APIs to develop a batch processing implementation framework with container functions. The client can dynamically add Web service call requests to the container. For example, the client can dynamically add addThirdPartyNonHostAccount, the getuserpendingconfigurications two Web services are added to this container and then initiate a batch processing Web service call request provided by a framework. The batch processing Web Service parses the container at the implementation end, extracts and parses various Web service requests, and starts an independent thread for processing.

Compressing SOAP

When the Web Service SOAP message body is large, we can improve the network transmission performance by compressing soap. Use GZIP to compress SOAP messages to obtain binary data and transmit binary data as attachments. In the past, the conventional method was to encode binary data with Base64, but the size after Base64 encoding is 1.33 times that of binary data. The hard compression is almost offset by Base64. Can binary data be directly transmitted? The mtom of the JAX-WS is acceptable, through the MIME specification of HTTP, SOAP message can be character, binary mix. We register a handler on each client and server to handle compression and decompression. Because the compressed SOAP message attachment is not automatically associated with the part of the message body based on MTOM, you need to process the attachment separately. Enable MTOM is required when generating client and server code. The specific Handler code is included in the Code attachment of this article, test. TestClientHanlder, test. TestServerHanlder. After writing the handler, you must register the handler for the service.

The client handler sample code is as follows:

Client code

Public boolean handleMessage (MessageContext arg0 ){

SOAPMessageContext ct = (SOAPMessageContext) arg0;

Boolean isRequestFlag = (Boolean) arg0

. Get (MessageContext. MESSAGE_OUTBOUND_PROPERTY );

SOAPMessage msg = ct. getMessage ();

If (isRequestFlag ){

Try {

SOAPBody body = msg. getSOAPBody ();

Node port = body. getChildNodes (). item (0 );

String portContent = port. toString ();

NodeList list = port. getChildNodes ();

For (int I = 0; I <list. getLength (); I ++ ){

Port. removeChild (list. item (I ));

}

ByteArrayOutputStream outArr = new ByteArrayOutputStream ();

GZIPOutputStream zip = new GZIPOutputStream (outArr );

Zip. write (portContent. getBytes ());

Zip. flush ();

Zip. close ();

Byte [] arr = outArr. toByteArray ();

TestDataSource ds = new TestDataSource (arr );

AttachmentPart attPart = msg. createAttachmentPart ();

AttPart. setDataHandler (new DataHandler (ds ));

Msg. addAttachmentPart (attPart );

} Catch (SOAPException e ){

E. printStackTrace ();

} Catch (IOException e ){

E. printStackTrace ();

}

}

Return true;

}

The Web server handler sample code is as follows:

Server code

Public boolean handleMessage (MessageContext arg0 ){

SOAPMessageContext ct = (SOAPMessageContext) arg0;

Boolean isRequestFlag = (Boolean) arg0

. Get (MessageContext. MESSAGE_OUTBOUND_PROPERTY );

SOAPMessage msg = ct. getMessage ();

If (! IsRequestFlag ){

Try {

Object obj = ct. get ("Attachments ");

Attachments atts = (Attachments) obj;

List list = atts. getContentIDList ();

For (int I = 1; I <list. size (); I ++ ){

String id = (String) list. get (I );

DataHandler d = atts. getDataHandler (id );

InputStream in = d. getInputStream ();

ByteArrayOutputStream out = new ByteArrayOutputStream ();

GZIPInputStream zip = new GZIPInputStream (in );

Byte [] arr = new byte [1024];

Int n = 0;

While (n = zip. read (arr)> 0 ){

Out. write (arr, 0, n );

}

Document doc = DocumentBuilderFactory. newInstance ()

. NewDocumentBuilder ()

. Parse (new ByteArrayInputStream (out. toByteArray ()));

SOAPBody body = msg. getSOAPBody ();

Node port = body. getChildNodes (). item (0 );

Port. appendChild (doc. getFirstChild (). getFirstChild ());

}

} Catch (SOAPException e ){

E. printStackTrace ();

} Catch (IOException e ){

E. printStackTrace ();

} Catch (SAXException e ){

E. printStackTrace ();

} Catch (ParserConfigurationException e ){

E. printStackTrace ();

}

}

Return true;

}

Add handler. Server handler in service-ref in web. xml.

Configuration code

<Handler-chains>

<Handler-chain>

<Handler>

<Handler-name> TestClientHandler

<Handler-class> test. TestClientHandler

</Handler-class>

</Handler>

</Handler-chain>

</Handler-chains>

Conclusion

Based on my experience and analysis, the above three solutions are proposed to address the performance bottleneck currently faced by Web Services. In addition, these solutions have achieved good results in actual project use. To sum up, in actual projects, one or more combinations of the above methods can be used according to different requirements to optimize the Web service performance.

Source: bole online

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.