标签:
这里我们来看看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}</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>
<!--使用自动注入的时候要 添加他来扫描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>
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<!--使用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":"' + $('#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 (控制层)
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;
}
}
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);
}
}
异步开始-----------》》》 end1 异步结束-----------》》》
ok 到此就结束了,代码写的比较简单,如有错误还请指教 谢谢……
标签:
原文地址:http://blog.csdn.net/qh_java/article/details/51905920