Chapter 2 _ asynchronous processing and Chapter 2 asynchronous Processing

Source: Internet
Author: User
Tags configuration settings rounds

Chapter 2 _ asynchronous processing and Chapter 2 asynchronous Processing
13.1 Overview

The computer memory is limited. Servlet/JSP Container designers are aware of this, so they provide some configuration settings to ensure that the container can run normally on the host machine. For example, in Tomcat 7, the maximum number of threads for processing incoming requests is 200. If it is a multi-processor server, you can safely increase the number of threads, but we recommend that you use this default value as much as possible.

Servlet or Filter occupies the request processing thread until it completes the task. If it takes a long time to complete the task, the number of concurrent users will exceed the number of threads, and the container will experience the risk of exceeding the thread. In this case, TOmcat will stack the excess requests in an internal server Socket (the Processing Methods of other containers may be different ). If more requests continue, they will be rejected until resources can process the requests.

Asynchronous processing can help you save container threads. This feature is suitable for long-running operations. Its job is to wait for the task to complete and release the request processing thread so that another request can use this thread. Note that asynchronous support is only applicable to long-running tasks, and you want to let users know the task execution result. If you only have tasks that run for a long time but do not need to know the processing result, you only need to provide a Runnable to the Executor and return immediately. For example, if you need to generate a report and send the report via email after the guard is ready, asynchronous processing is not suitable. On the contrary, if you need to generate a report and display it to users after the report is complete, you can use Asynchronous processing.

 

13.2 write asynchronous Servlet and Filter

The annotation types of WebServlet and WebFilter can contain the new asyncSupport attribute. To write Servlet and Filter that supports asynchronous processing, the asyncSupported attribute must be set to true:

@ WebServlet (asyncSupported = true ...)

@ WebFilter (asyncSupported = true ...)

Another configuration in the configuration file

<Servlet>

<Servlet-name> AsyncServlet </servlet-name>

<Servlet-class> servlet. MyAsyncServlet </servlet-class>

</Servlet>


13.3 compile an asynchronous Servlet

Writing asynchronous Serlvet or Filter is relatively simple. If you have a task that takes a relatively long time to complete, you 'd better create an asynchronous Servlet or Filter. In the asynchronous Servlet or Filter class, you need to do the following:

1. Call the startAsync method in ServletRequest. StartAsync returns an AsyncContext.

2. Call the setTimeout () method in AsyncContext to set the number of milliseconds that a container must wait for the specified task to complete. This step is optional, but if this time limit is not set, the default time of the container will be used. If the task fails to be completed within the specified time limit, an exception is thrown.

3. Call asyncContext. start to pass the Runnable of a long-time task.

4. When the task is completed, use Runnable to call the asyncContext. complete method or asyncContext. dispatch method.

The following is the main content of the doGet or doPost method of asynchronous Servlet:

Final AsyncContext asyncContext = servletRequest. startAsync ();

AsyncContext. setTimeout (...);

AsyncContext. start (new Runnable (){

@ Override

Public void run (){

// Long running task

AsyncContext. complete () or asyncContext. dispatch ()

}

})

The following is an example:

AsyncDispatchServlet. java

package servlet;import java.io.IOException;import javax.servlet.AsyncContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet(name="AsyncDispatchServlet", urlPatterns={"/asyncDispatch"},asyncSupported=true)public class AsyncDispatchServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overridepublic void doGet(final HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{final AsyncContext asyncContext = request.startAsync() ;request.setAttribute("mainThread", Thread.currentThread().getName());asyncContext.setTimeout(5000);asyncContext.start(new Runnable(){@Overridepublic void run() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}request.setAttribute("workerThread", Thread.currentThread().getName());asyncContext.dispatch("/ThreadNames.jsp");}});}}

ThreadNames. jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Running result:



In the following example, the Servlet sends a process update every second so that the user can track the process. It sends HTML responses and a simple javaScript code to update an HTML div element.

AsyncCompleteServlet. java

package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.AsyncContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AsyncCompleteServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");final PrintWriter writer = response.getWriter() ;writer.println("

Deployment configuration file

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  <display-name>AsyncServlet</display-name>  <servlet>  <servlet-name>AsyncComplete</servlet-name>  <servlet-class>servlet.AsyncCompleteServlet</servlet-class>  <async-supported>true</async-supported>  </servlet>  <servlet-mapping>  <servlet-name>AsyncComplete</servlet-name>  <url-pattern>/asyncComplete</url-pattern>  </servlet-mapping></web-app>


Running result:


13.4 asynchronous listener

In addition to supporting asynchronous Servlet and Filter Operations, Servlet3.0 also adds an AsyncListener interface to notify users of events that occur during asynchronous processing. The AsyncListener interface defines the following methods. when an event occurs, a method is called.

Void onStartAsync (AsyncEvent event)

This method is called when an asynchronous operation is started.

Void onComplete (AsyncEvent event)

This method is called when an asynchronous operation is complete.

Void onError (AsyncEvent event)

This method is called when an asynchronous operation fails.

Void onTimeout (AsyncEvent event)

This method is called when an asynchronous operation has timed out, that is, when it fails to be completed within the specified time limit.

All the four methods will receive an AsyncEvent event. You can obtain related AsyncContext, ServletRequest, and ServletResponse instances by calling its getAsyncContext, getSuppliedReqeust, and getSuppliedResponse methods respectively.

The following example differs from other Web listeners in that it does not use @ WebListener to mark AsyncListener.

MyAsyncListener. java

package listener;import java.io.IOException;import javax.servlet.AsyncEvent;import javax.servlet.AsyncListener;public class MyAsyncListener implements AsyncListener{@Overridepublic void onComplete(AsyncEvent arg0) throws IOException {// TODO Auto-generated method stubSystem.out.println("MyAsyncListener.onComplete()");}@Overridepublic void onError(AsyncEvent arg0) throws IOException {// TODO Auto-generated method stubSystem.out.println("MyAsyncListener.onError()");}@Overridepublic void onStartAsync(AsyncEvent arg0) throws IOException {// TODO Auto-generated method stubSystem.out.println("MyAsyncListener.onStartAsync()");}@Overridepublic void onTimeout(AsyncEvent arg0) throws IOException {// TODO Auto-generated method stubSystem.out.println("MyAsyncListener.onTimeout()");}}

AsyncListenerServlet. java

package servlet;import java.io.IOException;import javax.servlet.AsyncContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import listener.MyAsyncListener;@WebServlet(name="AsyncListenerServlet",urlPatterns={"/asyncListener"},asyncSupported=true)public class AsyncListenerServlet extends HttpServlet{private static final long serialVersionUID = 1L;@Overridepublic void doGet(final HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {final AsyncContext asyncContext = request.startAsync() ;asyncContext.setTimeout(5000);asyncContext.addListener(new MyAsyncListener());asyncContext.start(new Runnable(){@Overridepublic void run() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}String greeting = "hi from listener" ;System.out.println("wait...");request.setAttribute("greeting", greeting);asyncContext.dispatch("/index.jsp");}});}}



The flame of the arms magic light stone 13th chapter full strategy

Strategy:
Different from the traditional survival chapter, it is easier to pass through this chapter by directly taking the mark ++ BOSS (AAS/BOSS) down rather than making it through 11 rounds, the reason is that after the end of the eight rounds, the enemy's reinforcements are the new force led by the old man balaro. Although others are not concerned about it, the magic of zookeeper is very high, but it is normal to have a remote light magic, and a companion who has not specialized in training the class can be killed by a blow. Relatively speaking, there are a lot of swordsmen, and it will be done twice with magic, but the musical killer has been found in the musical fighters, another mountain thief is taking physical medicine and doesn't feel uncomfortable if he doesn't take it. So let's get ready for the lineup. At the beginning, dancing was used to kill the two arrows above, and the following were directly under the cavalry attack range. Other people use the terrain in the middle to set up positions and other enemies. After the first wave of enemies is eliminated, the enemy with the sleep stick is first handled, and then three companions occupy the areas between the recovery point and the station to resist the enemy reinforcements, if you have enough manpower, it would be better to go out and clear all the ronts. The left side of the enemy reinforcement is not strong until the appearance of zookeeper (KU Ge), it is well known that the next round he was talking about zookeeper. Next, we should prepare to deal with zookeeper. All the weak companions will be near the recovery point on the right, so that we can easily run the road at that time. Of course, we can easily hide it at the upper right or lower right corner of the Road exit. The thieves stole the Red dragonfly from the enemy and then returned to the intermediate standby mode. If the thief HP and the magic defense are insufficient, use the previous chapter to obtain the mシル magic defense, another two or three strong companions are with thieves. On the other hand, it is best to hit him first to almost fall down, to ensure that after the robbery is over, a single blow is taken away. It should have been time to show up, so we should calculate the scope and damage of the remote magic attack, so as not to be killed by a companion. Of course, it would be much easier to stand in front of them if there is plenty of time, and avoid being attacked by zookeeper first. When they arrived, the thieves stole the medicine, and the other companions fought and died, and then they could pass the fight.

TIPS:
★☆Make good use of the terrain to get twice the result with half the effort, and do not make the enemy happy to use the three bows and arrows.
★☆The flying dragon knight can be said by the hacker, and pay attention to his attack scope to avoid accidental injury.
★☆If she hasn't mentioned this before, she will see it again in this chapter. It can also be said by the author, and author.

Enemy:

LV12 gunshots * 3 (iron gun) LV10 God Officer * 1 (healing pin red Sec)

LV13 God Officer * 1 (sleep pin) LV11 Archer * 4 (iron bow)

LV12 Knight * 4 (iron gun) LV12 heavy armor server * 4 (iron gun)

LV3 jungle Knight * 1 (steel sword) LV2 jungle Knight * 1 (steel bow)

LV2 jungle Knight * 1 (steel sword) LV5 newcomer soldier amilia)

Enemies of HARD difficulty append:

LV12 gunshots * 3 (iron) LV11 Archer * 2 (iron)

LV12 mercenary * 1 (tiejian)

BOSS:

LV9 heavy knight (silver sword and gun knight medal)

Enemy reinforcements:

At the beginning of the 2nd round

LV12 mercenary * 1 (chopped horse knife) LV13 warrior * 1 (iron Ax)

At the beginning of the three rounds, replace the reinforcements on the top left:

LV12 mercenary * 1 (ijian) LV12 warrior * 1 (iron Ax)

Three times in total

At the beginning of the 5th round, the bottom left Mountain, and five forges near the BOSS:

Ku Ge LV11 dragon knight)

LV10 dragon Knight * 2 (steel gun)

Fortress:

LV12 Knight * 3 (iron gun) LV12 Knight * 1 (iron sword)

LV11 server guard * 1 (iron gun)

The enemies here are reinforced at the beginning of Round 5, 7, and 9.

At the beginning of the 9th round, balaro's reinforcements appeared on the left:

LV12 thief * 3 (iron Ax) LV12 thief * 1 (poison axe build ring)

LV2 warrior * 1 () LV12 * 2 ()

LV11 magician * 2 (huoyan)

BOSS

LV5 Xian ...... remaining full text>

Introduction to the holy light stone in flame Articles Chapter 4

It looks like the heroine's route and there are no novice soldiers in Chapter 9. The novice soldiers and Ku Ge both let the heroine collect it. Ku Ge is strong in mobility, it is best to let him leave the mountain and use the dancing girl's re-motion to let the main character run to him in one round. Otherwise, it is not your man who will kill the gun and suffer heavy losses, that is, Ku's own life. You can select all the characters that are relatively strong, go forward at full speed and use special-effect weapons to kill the boss that emerged from the very beginning (the survival of the magic light stone ends as long as the master boss is killed)

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.