Spring 3 and later versions of Async

Source: Internet
Author: User

Here we look at the supported @async (method Async) in Spring 3.0 and later releases

In fact, in the previous program has not seen the use of @async, recently contacted, thinking if the use of asynchronous cache is not the response speed will greatly improve that, such as you go to query, found that there is no data in the cache, you want to get the data from the database, and then to put the data into the cache before the data to show the foreground, This step of putting data into the cache takes up a part of the time, so that the foreground display is slower, so if you save to the cache this step uses asynchronous processing that can save this part of the time, the response speed is relatively faster, ha haha personally understand if there is wrong place also please advise ...

Let's take a look at the small demo to learn how to use

I. Define a method of the service layer as an async method in a Web project

Here's the code for this project:

1. Web. XML configuration

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "><display-name>website2</ display-name><!--Load Spring container configuration--><listener><listener-class> org.springframework.web.context.contextloaderlistener</listener-class></listener><!-- Set Spring container load profile path--><context-param><param-name>contextconfiglocation</param-name><         Param-value> Classpath:config/springmvc-servlet.xml, Classpath:config/applicationcontext.xml </param-value></context-param><!--character encoding filter--><filter><filter-name>encodingfilter </filter-name><filter-class>org.springframework.web.filter.characterencodingfilter</ Filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param>< Param-name>forceencoding</param-name><param-value>true</param-value></init-param> </filter><filter-mapping><filter-name>encodingfilter</filter-name><url-pattern>* .do</url-pattern></filter-mapping><!--Front-end controller--&GT;&LT;SERVLET&GT;&LT;SERVLET-NAME&GT;SPRINGMVC </servlet-name><servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class ><init-param><param-name>contextconfiglocation</param-name><param-value>classpath: config/springmvc-servlet.xml</param-value></init-param><!--This configuration file is loaded when the container is started-->< Load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name> springmvc</servlet-name><!--Intercept Request--><url-pattern>*.do</url-pattern></servlet-mapping ><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file>< welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file>< welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></ Welcome-file-list></web-app>


2. Applicationcontext.xml configuration file

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:task= "Http://www.springframework.org/schema/task" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.or G/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd/HTTP                  WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2 . xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ";<!--Load configuration jdbc file--><context:property-placeholder location= "classpath:db.properties"/><!--data Source-- ><bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" ><property Name= "Driverclassname" ><value>${jdbc.driverclassname}</value></property><property name= "url" ><value>${jdbc.url}</value></property><property name= "username" ><value>${ Jdbc.username}</value></property><property name= "Password" ><value>${jdbc.password}</ value></property></bean><!--Use automatic injection when you want to add him to scan the beans before they can be used--><context:component-scan Base-package= "Com.website.service, Com.website.dao"/><!--use MyBatis when using Sqlsessionfactorybean To manage MyBatis's sqlsessionfactory--><!--and like this using the interface implementation is done using Sqlsessiontemplate, he provides some methods--><bean id= " Sqlsessionfactory "class=" Org.mybatis.spring.SqlSessionFactoryBean "><property name=" DataSource "ref=" dataSource "/><!--mybatis configuration file path--><property name=" configlocation "value=" "/><!--entity class mapping file path, The mapping file must be multiple in development so use Mybatis/*.xml instead of--><property name= "mapperlocations" value= "classpath:mybatis/ Usermapping.xml "/></bean><!--actually the example of the class here is MyBatis sqlsession--><bean id=" sqlsession "class=" Org.mybatis.spring.SqlSessionTemplate "><constructor-arg index=" 0 "><ref bean=" Sqlsessionfactory "/> </constructor-arg></bean><!--Simple definition of asynchronous @async using spring--<!--<task:annotation-driven/ >-<!--asynchronous definition recommended-<task:executor id= "executor" pool-size= "/><task:scheduler id=" Sche Duler "pool-size=" "/><task:annotation-driven executor=" executor "scheduler=" Scheduler "/><!--define transaction manager --><bean id= "TransactionManager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" ><property name= "DataSource" ref= "DataSource"/></bean><!--use AOP facets below to implement--><tX:advice id= "Testadvice" transaction-manager= "TransactionManager" ><!--Configure transaction propagation, isolation levels, and time-out rollback issues--&GT;&LT;TX: Attributes><tx:method name= "save*" propagation= "REQUIRED"/><tx:method name= "del*" propagation= " REQUIRED "/><tx:method name=" update* "propagation=" REQUIRED "/><tx:method name=" add* "propagation=" REQUIRED "/><tx:method name=" * "rollback-for=" Exception "/></tx:attributes></tx:advice>< aop:config><!--Configuring transaction pointcuts--><aop:pointcut id= "services" expression= "Execution (* com.website.service.*.* (..))" /><aop:advisor pointcut-ref= "Services" advice-ref= "Testadvice"/></aop:config></beans>

Note here that when using spring's async, there are:

xmlns:task= "Http://www.springframework.org/schema/task"
Http://www.springframework.org/schema/task                 http://www.springframework.org/schema/task/spring-task-3.2.xsd

These three are necessary, and configure one of the following two to define the @async async method

<!--simple definition of asynchronous @async using spring--    <!--  <task:annotation-driven/>--    <!-- Asynchronous definition recommended-  -    <task:executor id= "executor" pool-size= "/><task:scheduler id=" Scheduler " Pool-size= ""/><task:annotation-driven executor= "executor" scheduler= "Scheduler"/>
OK except the two others are the same as the other spring general configuration is no different.


3, SPRINGMVC configuration:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "Http://www.springframework.org/schema/aop" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xmlns:util= "Http://www.springframework.org/schema/util" xmlns:tx= "Http://www.springframework.org/schema/tx" Xmlns:jdbc= "Http://www.springframework.org/schema/jdbc" xmlns:cache= "http://www.springframework.org/schema/ Cache "Xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ BEANS/SPRING-BEANS-3.1.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ spring-mvc-3.1.xsdhttp://wWw.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsdhttp:// Www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsdhttp:// Www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsdhttp:// Www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd "><! --note driver--><mvc:annotation-driven/><!--scan--><context:component-scan base-package= " Com.website.controller "></context:component-scan><!--View resolver--><bean id=" Viewresolver "class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" prefix "value="/web-inf /view/"></property><property name=" suffix "value=". JSP "></property></bean></beans  >

4. MyBatis Mapping File Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public    "-//mybatis.org//dtd mapper 3.0//en"        "HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" >        <!--This namespace + ID is a complete path, after we have written the complete path in the DAO layer, MyBatis is mapping the relevant SQL statement in this file--><mapper namespace= " Com.website.userMapper "><!--parametertype is the type of parameter you accept,  --><!--Add user information--><insert id=" Insertuser "  parametertype=" Java.util.Map "> Insert  into  User (Id,name,password)  values (#{id},# {Name},#{password}) </insert></mapper>

5. Db.properties Configuration

Jdbc.driverclassname=com.mysql.jdbc.driver  jdbc.url=jdbc:mysql://localhost:3306/user?useunicode=true& Characterencoding=utf8jdbc.username=rootjdbc.password=admin


OK to here all the configuration files are gone, you may also find, in fact, and we usually configure the very thought, in addition to the two applicationcontext.xml in the other is the same.


Let's take a look at the code and see what's different than async:

6. Front-End Request code:

function Profilep () {//Assemble JSON format data var MyData = ' {' name ': ' ' + $ (' #name '). Val () + ' "," id ":" ' + $ (' #id '). Val () + ' "," password " : "' + $ (' #password '). Val () + '"} '; $.ajaxsetup ({contentType: ' Application/json '}); $.post (' Http://localhost:18080/website2/user/save2.do ', mydata,function (data) {alert ("ID:" + data.id + "\nname:" + Data.name+ "\password:" + Data.password);}, ' json ');}


7. Controller (Control layer)

Package Com.website.controller;import Java.util.hashmap;import Java.util.map;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestbody;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.responsebody;import Com.website.po.user;import com.website.service.userservice;/** * @author WHD Data June 5, 2016 */@Controller @requestmapping (value = "/user") public Class Usercontroller {@Autowiredprivate userservice userservice; @RequestMapping (value = "/list.do") Public String list ( {return "info";} @ResponseBody @requestmapping (value = "/save2.do", method = Requestmethod.post)//confidant receives the object, because @requestbody Spring helps us deal with This process of protocol-to-object public user Info2 (@RequestBody user user) {String id = User.getid(); String name = User.getname (); String password = User.getpassword (); map<string, string> map = new hashmap<string, string> (), Map.put ("id", id), Map.put ("name", name), Map.put (" Password ", password); the try {//Async method executes the Async method first, but the asynchronous method executes for a long time, so the synchronous method executes the Userservice.async () during asynchronous method execution;// Synchronization method Userservice.saveuser (map);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} User user2= New User (Id,name,password),//return object directly, because @responsebody Spring will help us deal with the conversion between the object and the Protocol return User2;}

The Info2 method is executed when the current-side request arrives, where the two service tier method is called, one is the asynchronous method, the other is the synchronous method, and the service layer code is shown below.


8. Service Layer

Package Com.website.service;import Java.util.map;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.scheduling.annotation.async;import Org.springframework.stereotype.service;import com.website.dao.userdao;/** * @author WHD Data June 5, 2016 * * @Service ("UserService") public class UserService {@ Autowiredprivate Userdao userdao;public void Saveuser (map<string, string> Map) throws Exception {Userdao.saveuser (map);} @Asyncpublic void Async () {System.out.println ("Asynchronous Start-----------"), try {thread.sleep (10*1000);} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("End of Asynchronous-----------");}}
You may find that the service layer differs from the previous one in that there is a @async on the async method and there is no synchronization method, so the method is not defined as an async method and processing adds a task to the Applicationcontext.xml configuration file and the task annotations are @async on the Async method, and the others are the same.

9. DAO Layer

Package Com.website.dao;import Java.util.map;import Org.mybatis.spring.sqlsessiontemplate;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.stereotype.repository;/** * @ Author WHD Data June 5, 2016 */@Repository ("Userdao") public class Userdao {@Autowiredprivate sqlsessiontemplate sqlsession ;p ublic void Saveuser (map<string, string> Map) {int end = Sqlsession.insert ("Com.website.userMapper.insertUser", MAP); System.out.println ("End" + End);}}

OK to here so the code is over, let's look at the code execution when printed results:

Asynchronous start-----------"End1 Asynchronous End-----------" "

OK see this method to know, this asynchronous method executes, first began to execute the async method, because he is an asynchronous method, so at the same time began to execute the synchronous method, but the asynchronous method execution time is long, so the synchronous method ends long after the asynchronous method ends, this is an asynchronous execution effect, This is the result we want!


OK to this end, the code is relatively simple to write, if there are errors please advise thank you ...




Spring 3 and later versions of Async

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.