这里我们来看看spring 3.0 以及以后版本中支持的@Async (方法异步)
其实在之前的程序中也没看到过有使用@Async 的,最近才接触到,想着如果使用异步缓存是不是响应速度会大幅提升那,就比如你去查询,发现缓存中没有数据,你要从数据库中获取数据,然后要把数据放到缓存中然后才能将数据展示到前台,其中将数据放到缓存的这个步骤占用了一部分时间,这样的话前台展示就比较慢了,所以如果保存到缓存这步使用异步处理方式那就可以节省这部分时间,响应速度相对会快一点,哈哈哈 个人理解如果有不对的地方还请指教……
下面来看看小demo 学学怎么使用
一、在web项目中将service 层的某个方法定义为异步方法
这里吧这个工程代码都贴出来吧:
1、web.xml 配置
- <?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>
- <!– 加载spring容器配置 –>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!– 设置Spring容器加载配置文件路径 –>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath:config/springmvc-servlet.xml,
- classpath:config/ApplicationContext.xml
- </param-value>
- </context-param>
- <!– 字符编码过滤器 –>
- <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>
- <!– 前端控制器 –>
- <servlet>
- <servlet-name>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>
- <!– 这个配置文件在容器启动的时候 就加载 –>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <!– 拦截请求 –>
- <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 配置文件
- <?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.org/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">
-
- <!-- 加载配置JDBC文件 -->
- <context:property-placeholder location="classpath:db.properties" />
- <!-- 数据源 -->
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName">
- <value>${jdbc.driverClassName}<span class="hljs-tag"></<span class="hljs-name">value</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="26"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"></<span class="hljs-name">property</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="27"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="28"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"><<span class="hljs-name">value</span>></span>${jdbc.url}</value>
- </property>
- <property name="username">
- <value>${jdbc.username}<span class="hljs-tag"></<span class="hljs-name">value</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="32"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"></<span class="hljs-name">property</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="33"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>></span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="34"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-tag"><<span class="hljs-name">value</span>></span>${jdbc.password}</value>
- </property>
- </bean>
- <!--使用自动注入的时候要 添加他来扫描bean之后才能在使用的时候 -->
- <context:component-scan base-package="com.website.service ,com.website.dao" />
- <!-- 在使用mybatis时 spring使用sqlsessionFactoryBean 来管理mybatis的sqlsessionFactory -->
- <!-- 而像这种使用接口实现的方式 是使用sqlsessionTemplate来进行操作的,他提供了一些方法 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <!-- mybatis配置文件路径 -->
- <property name="configLocation" value="" />
- <!-- 实体类映射文件路径,在开发中映射文件肯定是多个所以使用mybatis/*.xml来替代 -->
- <property name="mapperLocations" value="classpath:mybatis/UserMapping.xml" />
- </bean>
-
- <!--其实这里类的实例就是mybatis中SQLSession -->
- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
- <constructor-arg index="0">
- <ref bean="sqlSessionFactory" />
- </constructor-arg>
- </bean>
-
- <!--使用spring的异步@Async简单定义方式 -->
- <!-- <task:annotation-driven /> -->
- <!--异步定义推荐方式 -->
- <task:executor id="executor" pool-size="15" />
- <task:scheduler id="scheduler" pool-size="30" />
- <task:annotation-driven executor="executor" scheduler="scheduler" />
- <!-- 定义事务管理器 -->
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!-- 下面使用aop切面的方式来实现 -->
- <tx:advice id="TestAdvice" transaction-manager="transactionManager">
- <!--配置事务传播性,隔离级别以及超时回滚等问题 -->
- <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>
- <!--配置事务切点 -->
- <aop:pointcut id="services"
- expression="execution(* com.website.service.*.*(..))" />
- <aop:advisor pointcut-ref="services" advice-ref="TestAdvice" />
- </aop:config>
- </beans>
这里注意,在使用spring的异步的时候要有:
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
这三个是必须要有的,而且要配置下面两种中的一种,来定义@Async 异步方法
- <!--使用spring的异步@Async简单定义方式 -->
- <!-- <task:annotation-driven /> -->
- <!--异步定义推荐方式 -->
- <task:executor id="executor" pool-size="15" />
- <task:scheduler id="scheduler" pool-size="30" />
- <task:annotation-driven executor="executor" scheduler="scheduler" />
ok 除了这两个其他的都和其他的spring一般配置是一样的没有什么不同。
3、springmvc 配置:
- <?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.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
- http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
- http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
-
- <!-- 注解驱动 -->
- <mvc:annotation-driven />
- <!-- 扫描 -->
- <context:component-scan base-package="com.website.controller"></context:component-scan>
- <!-- 视图解析器 -->
- <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 的映射文件配置
- <?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">
- <!--这个namespace + 下面的id 就是一个完整的路径,在dao层我们写了完整的路径之后mybatis就是映射这个文件中的相关sql语句 -->
- <mapper namespace="com.website.userMapper">
- <!-- parameterType就是你接受的参数的类型, -->
- <!-- 添加用户信息 -->
- <insert id="insertUser" parameterType="java.util.Map">
- insert into user(id,name,password) values(#{id},#{name},#{password})
- </insert>
- </mapper>
5、db.properties 配置
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=admin
ok 到这里所有的配置文件都全了,你可能也发现了,其实和我们平时配置的很像,除了applicationContext.xml 中的那两处不同之外其他的都是一样的。
下面我们来看看代码,看看和不是异步的有什么不同之处:
6、前端请求代码:
- function profilep() {
- // 组装json格式数据
- var mydata = '{"name":"' + $(<span class="hljs-string">'#name'</span>).val() + <span class="hljs-string">'","id":"'</span></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="4"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> + $('#id').val() + '","password":"' + $(<span class="hljs-string">'#password'</span>).val()</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="5"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> + <span class="hljs-string">'"}'</span>;</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="6"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> $.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 (控制层)
- 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 2016年6月5日
- */
- @Controller
- @RequestMapping(value = "/user")
- public class UserController {
- @Autowired
- private UserService userService;
-
- @RequestMapping(value = "/list.do")
- public String list() {
- return "info";
- }
-
- @ResponseBody
- @RequestMapping(value = "/save2.do" ,method = RequestMethod.POST)
- // 知己接收对象,因@RequestBody spring 帮我们处理了 协议到对象的这个过程
- 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);
- try {
- //异步方法,先执行的是异步方法,但是异步方法执行时间比较长,所以在异步方法执行期间同步方法在执行
- userService.async();
- //同步方法
- userService.saveUser(map);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- User user2= new User(id,name,password);
- // 直接返回对象,因@ResponseBody spring 会帮我们处理对象和协议之间的转化
- return user2;
- }
- }
当前端请求到来时执行info2 这个方法,其中就调用了两个service 层的方法即一个是异步方法一个是同步方法,下面看看service层的代码。
8、service 层
- 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 2016年6月5日
- */
- @Service("userService")
- public class UserService {
- @Autowired
- private UserDao userDao;
- public void saveUser(Map<String, String> map) throws Exception {
- userDao.saveUser(map);
- }
- @Async
- public void async(){
- System.out.println("异步开始-----------》》》");
- try {
- Thread.sleep(10*1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("异步结束-----------》》》");
- }
- }
-
你可能发现了,service 层和以往有所不同,那就是在异步方法上有@Async 而同步方法上就没有了,所以方法是否别定义为异步方法,处理在ApplicationContext.xml 配置文件中添加了task 以及task注解之外就是异步方法上的@Async 这个注解了,其他的都一样。
9、dao 层
- 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 2016年6月5日
- */
- @Repository("userDao")
- public class UserDao {
- @Autowired
- private SqlSessionTemplate sqlSession;
- public void saveUser(Map<String, String> map) {
- int end = sqlSession.insert("com.website.userMapper.insertUser", map);
- System.out.println("end" + end);
- }
- }
ok到这里所以的代码就完了,下面我们看看代码执行时打印的结果:
异步开始-----------》》》 end1 异步结束-----------》》》
ok 看到这个方法就知道了,这个异步方法执行了,首先开始执行异步方法,因为他是异步方法所以同时开始执行了同步方法,但是异步方法执行时间比较长,所以同步方法结束后很久异步方法才结束,这样就是一个异步执行的效果,这也是我们想要的结果!
二、spring3.0之后的定时任务中使用@Async
上面的代码是在springmvc+spring +mybatis 的web项目中使用了异步方法,而在spring3.0以及之后的版本中使用异步方法,下面我们来看看小demo
这里的定时任务和mybatis 或hibernate 没有进行整合,只是spring 简单来看看,因为整合不影响异步执行,只是多了上面说的那三个东西,即配置文件中的task 以及注解就可以了,所以下面就看看简单spring的定时任务的异步方法。
1、spring 的配置文件ApplicationContext.xml
- <?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:jee="http://www.springframework.org/schema/jee"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:task="http://www.springframework.org/schema/task"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/jee
- http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd"
- default-lazy-init="true">
-
- <description>Spring </description>
- <context:component-scan base-package="com.service" />
- <!-- 异步配置 -->
- <task:executor id="executor" pool-size="50" />
- <task:scheduler id="scheduler" pool-size="100" />
- <task:annotation-driven executor="executor"
- scheduler="scheduler" />
- <!-- 配置自定义任务 -->
- <bean name="scrapydTask" lazy-init="false" class="com.controller.Test"></bean>
- </beans>
这个是spring 配置文件,其中的和之前一样,要引入task 并且要有task注解。
因为这里是spring定时任务,所以要有定时任务的配置文件
ok 因为只是一个简单的spring定时任务所以也就只有一个spring配置文件,下面我们看看代码:
- package com.controller;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
-
- import com.service.Test2;
- @Component
- public class Test {
- @Autowired
- private Test2 test2;
- @Scheduled(cron = "0 0/1 * * * *")
- void schedule(){
- test2.asyncFun();
- test2.other();
- }
- }
我们看到这里有两个方法一个是异步方法,一个是同步方法,我们首先调用的是异步方法,之后调用了同步方法,所以我们想要的结果就是首先开始执行异步方法,当开始执行后接着执行同步方法,这样就不用等着异步方法执行完了在执行,如果添加缓存什么的我们就不用管了,所以这样的方法还是比较好的。当然我们也看到了那个定时任务的注解。
3、service层
- package com.service;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Service;
- @Service("test2")
- public class Test2 {
- @Async
- public void asyncFun(){
- System.out.println("------异步方法开始");
- try {
- Thread.sleep(15*1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("------异步方法结束");
- }
- public void other(){
- try {
- Thread.sleep(3*1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("同步方法");
- }
- }
看到这个方法中我们的异步方法有个@Async 这样的注解,这个注解就是使这个方法定义为一个异步方法。
4、执行结果:
这就是执行的结果,这是不是想要的那,是的这就是我们想要的异步执行!
5、ok到这里定时任务的异步就完成了,我们简单的总结一下,首先我们要在spring的配置文件中添加定时注解,异步注解,并且要在定义为异步方法的地方添加异步注解。
具体的配置可以参考上面的小demo
ok 到此就结束了,代码写的比较简单,如有错误还请指教 谢谢……