In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you the practical analysis of Java Web service performance optimization, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Introduction: how to improve the performance of Java Web services, this paper mainly introduces three methods: the first is to use asynchronous invocation of Web services, the second is to introduce Web service batch mode, and the third is to compress SOAP messages. Focuses on how to use asynchronous Web services during programming and the differences between asynchronous and synchronous invocations. This article also demonstrates how to use the above three methods in the project, as well as the application scenarios suitable for each method.
Introduction to Java Web Servic
Web service is a service-oriented architecture technology, which provides services through the standard Web protocol to ensure that application services on different platforms can be interoperable. Web Service (Web Service) is a kind of service based on XML and HTTP communication. Its communication protocol is mainly based on SOAP. The description of the service discovers and obtains the service metadata through WSDL and UDDI. This kind of Web service, which is based on XML standard and Internet protocol, is the next development direction of distributed computing. Web service brings a bright prospect for the communication and cooperation between commercial applications built by different resources, so that they can cooperate with each other without being affected by their underlying implementation schemes.
JAX-RPC 1.0 is the original standard of Web services in Java, but because there are some limitations in JAX-RPC 1.0's understanding of Web services, JAX-WS 2.0 comes into being. The main goal of the development work of JAX-WS 2.0 is to update the standards and successfully meet the industry expectations of JAX-RPC 1.x. In addition, JAX-WS 2.0 directly supports XOP/MTOM, which improves the ability of transferring system attachments and the interoperability between systems.
An example to analyze the bottleneck of Web service performance
From the above description, it is not difficult to realize that Web service, with its loose coupling and platform-independent characteristics of XML + HTTP, is doted on and will become the basis of data sharing in the future. But at the same time, we should also realize that everything in the world has its contradictory two sides: there are advantages and disadvantages, and so is Web service. Just like the fatal criticism of performance when JAVA became popular, Web services also faced performance problems, which seemed to be the lingering enemies of platform-independent. But the problem has to be solved in the end, and practice is the only way to test and analyze the problem. Let's first create a simple Web service and then examine and analyze the implied performance problems.
Create a service
Create a service Java Bean: first, we create a bookstore service Bean that is as simple as possible. The content of the service is only one qryBooksByAuthor, that is, the books under its name are queried by the author (Author) (List).
Figure 1. Bookstore service Bean (BookStoreSrvBean)
Entity class that serves the Input- author (Author):
Figure 2. Author entity class (Author)
Entity classes that serve the list of Output- books (Book):
Figure 3. Book entity Class (Book)
Now that our service code is complete, we will not discuss the business reasonableness of this service here, but only to give an example as simple as possible to analyze the performance of the web service.
The following task is to develop Web services. The process of manually writing and publishing Web services that conform to the specification is very tedious. Here, IBM Rational Software Architect (hereinafter referred to as RSA) is used for server-side and client-side development of Web services.
Publish Web services
Create a dynamic Web project: of course, a J2EE Web project is required to publish the Web service. Open RSA- > File- > New- > Dynamic Web Project, the project name is testWebService, and the remaining options are selected as needed (note that you need to choose to join the Web project to EAR). The effects of the created Web and EAR projects are as follows:
Figure 4. Structure of the Web project and the application project
Create a 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 the commonly used JAX-WS standard when you create it, and choose to generate the WSDL file. Since the creation of Web services is not the focus of this article, this section will be omitted for the time being. After the service is created, it can be published to the Web project built in the previous step.
Create a client
With RSA, the creation of the client will be very simple: right-click the WSDL file generated above-> Web Services- > Generate Client
Figure 5. Create a client interface
In this interface, select the target project of the server,JAX-WS standard and Client code according to the actual situation, and then click next.
Figure 6. Enter client information
This interface temporarily uses the default configuration, and some special options are described in later chapters.
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-side WSDL to make the Web service call with the following code. The purpose of modifying the WSDL port here is to let the client call the virtual port of TCP/IP Monitor provided by RSA so that we can easily see the actual invocation of the Web service and the SOAP message returned.
The client call code is as follows:
Figure 7. Client call code
The SOAP message you see using TCP/IP Monitor is as follows:
Figure 8. SOAP message generated by Web service invocation
Performance Analysis of Java Web Service
From the above examples, we can see that the invocation of Web services is quite different from the traditional RPC. The biggest feature is that both sides of the call use SOAP specification messages in XML format for transmission, so the advantage of text transmission is to abandon the private protocol. No matter what platform both parties are calling, as long as they can construct and parse XML text, and there is a transport protocol supported by both parties, then the call becomes possible. The increasing specification of XML and the popularity of HTTP protocol provide a strong backing for these two necessary conditions. It is an indisputable fact that Web service has become a general service provision standard in the future.
However, it is believed that people who have used Web services have experienced the dilemma of their poor performance, and the reason why we can analyze the following points with the example just now:
● SOAP text message conversion leads to inefficiency
From the request and response messages just monitored by TCP/IP Monitor, we can see that when sending the message, we passed in the Author object. When the actual call occurs, the Author object will be converted into a SOAP message in XML format, which will be parsed and reconstructed into an Author object on the Server side when it arrives at the Server end. The same goes for Response, and Books List goes through the process of XML serialization and deserialization. Worst of all, this process happens every time it is called, and this construction and parsing process consumes a lot of CPU and resources.
● SOAP text message transmission causes transmission content to swell
Take the request parameter Author as an example, the necessary information is only a few bytes of "Bruce Eckel", but after it is converted into a XML message, you can see from the SOAP message that there are a lot of SOAP specification tags, which will lead to a sharp increase in the content to be transmitted, and a few bytes are likely to become thousands of bytes. When the call frequency and parameter content increase, the expansion of transmission content will not be a negligible impact, it will not only eat up the network bandwidth, but also burden the data throughput capacity of Server, and the consequences can be imagined.
● synchronous blocking calls cause poor performance in some cases
Synchronous blocking call means that the client has been in the blocking state after calling the Web service to send request, and the client thread will hang and wait all the time, and can not handle other tasks. This will result in a waste of threads, and if the corresponding threads occupy some resources, they can not be released in time.
This problem is not obvious in the case of pure client access to the Server side, but if the Web service call is made between two Server sides, the blocking pattern will become the performance bottleneck of the calling Server side.
Practice of Web Service performance Optimization
Invoke web services asynchronously
First of all, it needs to be emphasized that the asynchronous mode here refers to the async of the client, regardless of whether the client is synchronous or asynchronous, it has no effect on the server. The ideal result we expect is that when the client sends the call request, it does not have to block waiting for the return result of the server side. This asynchronous invocation feature has been added to the latest JAX-WS standard, and the better news is that JAX-WS is also supported in the RSA tool, which greatly facilitates the creation of asynchronous invocation clients.
In fact, it is extremely simple to configure the client in asynchronous mode, as long as the 'Enable asynchronous invocation for generated client' is selected when RSA generates the Client code, as shown below:
Figure 9. Asynchronous client creation option
This adds qryBooksByAuthorAsync's asynchronous methods to the BookStoreSrvBeanService of the generated client. Since it is an asynchronous method, Call Back is essential. In the following asynchronous client test code, you can see the specific use of anonymous inner classes as callback handler:
Figure 10. Asynchronous client invokes sample code
The output 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 do its own output: "not done yet, can do something else..." . Some people may think that the output here as a client is of no practical significance, but imagine that if a server accesses a Web service as a client, if you have the opportunity to get out of the blocking state to execute the code you need while the service is waiting, or even use methods such as wait to release resources occupied by the current thread, then this will be an essential factor for performance improvement for this server.
Enable web services to support batch mode
Brief introduction of ● batch processing mode
As the name implies, batch processing uses multiple transactions at a time to replace the traditional processing method of one transaction at a time. A large number of batch API are available in Java Database Connectivty (JDBC) to optimize database operation performance, for example, Statement.executeBatch () can receive and execute multiple SQL statements at once. The idea of batch processing can be easily transplanted to the Web service invocation scenario to optimize the response of Web service invocation. Through the actual Web service call timestamp analysis, it is not difficult to see that network communication is one of the bottlenecks of Web service performance, so batch mode is one of the more direct ways to optimize Web service performance by reducing network communication overhead.
Adaptability of ● batch processing mode
Although batch mode works well, it is not suitable for all scenarios. There are several points to consider when using batch mode to process Web service requests:
1. Differences in execution time of different Web services
Different Web services have different execution times, so this time difference needs to be taken into account when processing multiple Web service requests at the same time. In general, after the execution of the Web service waiting for the longest processing time, the execution results of all Web services are summarized and returned to the client, so it is possible that batch processing of multiple Web services takes longer than a single sequential call to Web services. It is necessary to have a clear understanding of the performance of Web services before adopting batch mode, including Web services with similar performance parameters into batches as far as possible, while dealing with Web services with different execution times. It is generally recommended that multi-Web services with performance differences of less than 30% can be considered for batch processing. For example, in AccountWebService, there is a Web service getUserAccounts that gets a list of user accounts. It takes 15 seconds for this Web service to execute, and one of the UserWebService gets the pending notification of the user's current pending. It takes 2 seconds for this Web service to execute. We can see that the execution time of the two Web services is quite different, so in this case, we do not recommend that the two Web services be included in batch processing. On the other hand, there is a Web service addThirdPartyNonHostAccount in AccountWebService that adds a third-party user account, and the Web service takes 3 seconds to execute, so you can consider that you can call the getUserPendingNotifications Web service and addThirdPartyNonHostAccount in a batch at once.
two。 Business relevance of different Web services
In general, it is recommended to consider putting multi-Web services with business relevance into batch processing. Only multi-Web services with business relevance will involve the need to reduce the number of calls to improve the performance of the application system. For example, after adding a third-party account addThirdPartyNonHostAccount, the user will automatically send a notification of pending to the user by default to prompt the user to activate the increased account. Therefore, in this scenario, the addThirdPartyNonHostAccount Web service and getUserPendingNotifications Web service can be put into a batch. After the user has added the third-party account, the system automatically refreshes the pending notification area to prompt the user to activate the account. In UserWebService, there is a Web service getUserHostAccounts that obtains the user's main account and the Web service getUserNonHostAccounts,MetaDataService that obtains the user's tripartite account. There is a Web service getFinacialAgencyHolidays that obtains the holiday data of national financial institutions. Obviously, there is no business correlation between the Web service and getUserHostAccounts,getUserNonHostAccounts, so they should not be included in batch processing.
3. Try to avoid putting multiple Web services with dependencies into the same batch
Putting multiple dependent multi-Web services into the same batch needs to specially consider and deal with the dependencies between multiple Web services, so that these convenient Web services can not be executed concurrently and have to execute dependent Web services serially. In the most pessimistic case, the batch response time will be the sum of serial execution time of all Web services in the batch. In principle, even if there is a dependency between Web services in a batch, the batch invocation of multiple Web services can be realized by dynamically specifying the dependency. However, this will greatly increase the technical complexity of the batch implementation, so this is not recommended.
4. Multi-threaded processing of batch Web service requests
Batch mode generally processes multiple Web service invocation requests concurrently through multithreading on the service implementation side. The batch mode request is parsed by a centralized parser, then a separate thread is started for each Web service call to process the Web request, and there is a general thread manager to schedule different Web service execution threads, monitor thread execution progress, and so on. Summarize the Web service execution results and return them to the client after all thread execution is completed.
Implementation of ● batch processing
There are generally two ways to implement batch processing: static batch mode and dynamic batch mode:
The implementation of static batch mode is relatively simple, but relatively inflexible. The core idea of static batch processing is to get the purpose of batch processing by means of composite encapsulation on the basis of 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 request structure, which initializes the batch request data object when the client makes the batch call, and assigns the specific Web service request object to the batch request object attribute. Similarly, when a batch response data object is generated on the service implementation side, it is also generated and returned to the client by combining the responses of a specific Web service.
The implementation of dynamic batch mode is more complex, but it can also provide greater operational flexibility. Dynamic batch processing mode generally requires applications to develop batch implementation frameworks with container functions by using Java reflection API. The client can dynamically add Web service invocation requests to the container, for example, the client can dynamically add two addThirdPartyNonHostAccount,getUserPendingNotifications Web services to the container and then initiate a batch Web service invocation request provided by a framework. On the implementation side, the batch Web service parses the container and extracts and parses each Web service request in it and starts an independent thread to process it.
Compressed SOAP
When the Web Service SOAP message body is large, we can improve the network transmission performance by compressing the soap. Compress the SOAP message through GZIP to get the binary data, and then transmit the binary data as an attachment. In the past, the conventional method was to encode binary data Base64, but the size of Base64 is 1.33 times the size of binary data. The hard compression is almost offset by Base64. Can binary data be transferred directly? JAX-WS 's MTOM is OK, and through HTTP's MIME specification, SOAP message can be mixed with characters and binaries. We register a handler on each side of client and server to handle compression and decompression. Because the compressed SOAP message attachment is not automatically associated with the body of the message based on MTOM, the attachment needs to be processed separately. Enable MTOM is required when generating client-side and server-side code. Handler specific code in this article code attachment, test.TestClientHanlder, test.TestServerHanlder. After you have written the handler, you also have to register handler for service.
The client-side 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; } Web 服务端 handler 样例代码如下: 服务端代码 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. Handler to the service-ref section of web.xml. Handler is also added on the Server side.
Configuration code
The above content of TestClientHandler test.TestClientHandler is the practical analysis of Java Web service performance optimization. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.