spring 3以及之后的版本的异步

这里我们来看看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>

这里注意,在使用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":"' + $('#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;
	}
}

当前端请求到来时执行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 看到这个方法就知道了,这个异步方法执行了,首先开始执行异步方法,因为他是异步方法所以同时开始执行了同步方法,但是异步方法执行时间比较长,所以同步方法结束后很久异步方法才结束,这样就是一个异步执行的效果,这也是我们想要的结果!

ok  到此就结束了,代码写的比较简单,如有错误还请指教 谢谢……

时间: 2024-08-25 03:24:57

spring 3以及之后的版本的异步的相关文章

spring boot 1.5.4 定时任务和异步调用(十)

上一篇:spring boot1.5.4 统一异常处理(九) 1      Spring Boot定时任务和异步调用 我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信.邮件之类的操作,也可能会定时地检查和监控一些标志.参数等. spring boot定时任务spring-boot-jsp项目源码: https://git.oschina.net/wyait/springboot1.5.4.git 1.1  创建定时任务 在Spring Boot中编写定时

Spring官网下载各版本jar包

1:浏览器输入官网地址:http://spring.io/projects 2:点击如图树叶页面按钮.  3:点击如图小猫图片按钮.  4:查找downloading spring artifacts 链接点击.  5:查找Manually downloading spring distributions 下面的 http://repo.spring.io.链接点击.  6:鼠标点击左边>>符号展开菜单选择Artifacts选项.  7:选择子菜单下的libs-release-local 选项

Spring中@Async注解实现“方法”的异步调用

简单介绍: Spring为任务调度与异步方法执行提供了注解支持.通过在方法上设置@Async注解,可使得方法被异步调用.也就是说调用者会在调用时立即返回,而被调用方法的实际执行是交给Spring的TaskExecutor来完成. 开启@Async注解: <task:annotation-driven executor="annotationExecutor" /> <!-- 支持 @Async 注解 --> <task:executor id="

InstallShield 2012 Spring优惠升级到最新版本(2015.4.30之前)

InstallShield 2012 Spring即将EOF,所以仍在使用InstallShield 2012 Spring的用户请注意下面内容: InstallShield 2012 Spring升级到最新版本InstallShield 2014将可以享受优惠升级,截止时间2015年4月30号. 具体可咨询InstallShield中国区总代世全软件

Spring 4.2.2以上版本和swagger集成方案和踩过的坑

因为公司使用的spring版本太高,在集成swagger的时候会存在一些问题,而网上的很多实例大多都是版本比较低的,为了是朋友们少才坑,我这边将集成的过程记录一下: 1. 引入spring.swagger的相关jar包(springfox-swagger2.springfox-swagger-ui),在pom.xml中配置: Xml代码 io.springfox springfox-swagger2 2.4.0 org.springframework spring-core org.spring

spring boot 学习(十一)使用@Async实现异步调用

使用@Async实现异步调用 什么是"异步调用"与"同步调用" "同步调用"就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行:"异步调用"则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务. 通常情况下,"同步调用"执行程序所花费的时间比较多,执行效率比较差.所以,在代码本身不存在依赖关系的话,我们可以考虑通过"异步调用"的方式来并发执行. &q

Spring Cloud 升级最新 Finchley 版本,踩了所有的坑!

Spring Boot 2.x 已经发布了很久,现在 Spring Cloud 也发布了 基于 Spring Boot 2.x 的 Finchley 版本,现在一起为项目做一次整体框架升级. 升级前 => 升级后 Spring Boot 1.5.x => Spring Boot 2.0.2 Spring Cloud Edgware SR4 => Spring Cloud Finchley.RELEASE Eureka Server Eureka Server 依赖更新 升级前: <

spring官网上下载历史版本的spring插件,springsource-tool-suite

spring官网下载地址(https://spring.io/tools/sts/all),历史版本地址(https://spring.io/tools/sts/legacy). 注:历史版本下载的都是装好插件的eclipse,而非我们需要的插件 目前官网上提供的下载地址只有springsource-tool-suite-3.9.5 (sts-3.9.5).而且只针对eclipse版本为4.8.0和4.7.3a有用,其他版本的sts地址都没有,那么我们要怎么获得我们用的eclipse版本的sts

Spring Cloud Sleuth 之Greenwich版本全攻略

微服务架构是一个分布式架构,微服务系统按业务划分服务单元,一个微服务系统往往有很多个服务单元.由于服务单元数量众多,业务的复杂性较高,如果出现了错误和异常,很难去定位.主要体现在一个请求可能需要调用很多个服务,而内部服务的调用复杂性决定了问题难以定位.所以在微服务架构中,必须实现分布式链路追踪,去跟进一个请求到底有哪些服务参与,参与的顺序又是怎样的,从而达到每个请求的步骤清晰可见,出了问题能够快速定位的目的. 在微服务系统中,一个来自用户的请求先到达前端A(如前端界面),然后通过远程调用,到达系