spring 配置异步要点 @Async

一般可以简单的用@Async来配置一个异步方法。例如
 
/**
* 发送MIME格式的用户修改通知邮件
*/
@Async 
public void sendNotificationMail(Map keyValue,String toAddress,String subJect,String templateName) {

String[] toList={toAddress};        sendNotificationMail(keyValue,toList,subJect,templateName) ;
}
 

但是这么做只是简单做法,大概积累3封邮件以后就会堵塞线程。

所以要加上配置文件

<task:annotation-driven executor="myExecutor" scheduler="myScheduler" />
<task:executor id="myExecutor" pool-size="50" />
<task:scheduler id="myScheduler" pool-size="1000" />  
 

但是只这么做,会报错

Caused by: org.xml.sax.SAXParseException: The prefix "task" for element "task:annotation-driven" is not bound. 

核心还是在最后。

在配置文件的前面加上

<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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    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.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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"
        default-lazy-init="true">
 
里面的task段落加上就OK了
出处: http://www.cnblogs.com/clarkapp/

ps:貌似异步方法和调用异步方法的方法不能在同一个类中,测了一下在同一个类中没有异步效果

另外因为junit结束之后会结束jvm,所以写async的测试类的时候需要在最后加上Threda.sleep(10000)等待异步结束了才能看出效果

spring配置文件可以简单加一行<task:annotation-driven />就可以

web项目中的配置

在spring mvc3.2及以上版本增加了对请求的异步处理,是在servlet3的基础上进行封装的。

1、修改web.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
...
</web-app>
复制代码

1.1、声明version="3.0",声明web-app_3_0.xsd

1.2、为servlet或者filter设置启用异步支持:<async-supported>true</async-supported>,修改WEB应用的web.xml

复制代码
<!-- spring mvc -->
<servlet>
<servlet-name>SpringMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>...</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
复制代码

 

2、使controller类支持async

2.1、返回java.util.concurrent.Callable来完成异步处理

复制代码
package org.springframework.samples.mvc.async;
  
import java.util.concurrent.Callable;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.WebAsyncTask;
  
@Controller
@RequestMapping("/async/callable")
public class CallableController {
    @RequestMapping("/response-body")
    public @ResponseBody Callable<String> callable() {
  
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "Callable result";
            }
        };
    }
  
    @RequestMapping("/view")
    public Callable<String> callableWithView(final Model model) {
  
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                model.addAttribute("foo", "bar");
                model.addAttribute("fruit", "apple");
                return "views/html";
            }
        };
    }
  
    @RequestMapping("/exception")
    public @ResponseBody Callable<String> callableWithException(
            final @RequestParam(required=false, defaultValue="true") boolean handled) {
  
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                if (handled) {
                    // see handleException method further below
                    throw new IllegalStateException("Callable error");
                }
                else {
                    throw new IllegalArgumentException("Callable error");
                }
            }
        };
    }
  
    @RequestMapping("/custom-timeout-handling")
    public @ResponseBody WebAsyncTask<String> callableWithCustomTimeoutHandling() {
  
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "Callable result";
            }
        };
  
        return new WebAsyncTask<String>(1000, callable);
    }
  
    @ExceptionHandler
    @ResponseBody
    public String handleException(IllegalStateException ex) {
        return "Handled exception: " + ex.getMessage();
    }
  
}
复制代码

2.2、在异步处理完成时返回org.springframework.web.context.request.async.DeferredResult其他线程,例如一个JMS或一个AMQP消息,Redis通知等等:

复制代码
@RequestMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
  DeferredResult<String> deferredResult = new DeferredResult<String>();
  // Add deferredResult to a Queue or a Map...
  return deferredResult;
}
    
// In some other thread...
deferredResult.setResult(data);
// Remove deferredResult from the Queue or Map
复制代码

 

3、spring配置文件的修改

spring mvc的dtd的声明必须大于等于3.2

<mvc:annotation-driven>
<!--  可不设置,使用默认的超时时间 -->
    <mvc:async-support default-timeout="3000"/>
</mvc:annotation-driven>

引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用 多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题,本文将完成介绍@Async的用法。

1.  何为异步调用?

    在解释异步调用之前,我们先来看同步调用的定义;同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果。 异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕;而是继续执行下面的流程。

     例如, 在某个调用中,需要顺序调用 A, B, C三个过程方法;如他们都是同步调用,则需要将他们都顺序执行完毕之后,方算作过程执行完毕; 如B为一个异步的调用方法,则在执行完A之后,调用B,并不等待B完成,而是执行开始调用C,待C执行完毕之后,就意味着这个过程执行完毕了。

2.  常规的异步调用处理方式

    在Java中,一般在处理类似的场景之时,都是基于创建独立的线程去完成相应的异步调用逻辑,通过主线程和不同的线程之间的执行流程,从而在启动独立的线程之后,主线程继续执行而不会产生停滞等待的情况。

3. @Async介绍

   在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。

     如何在Spring中启用@Async

       基于Java配置的启用方式:

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Configuration  
  2. @EnableAsync  
  3. public class SpringAsyncConfig { ... }  
     基于XML配置文件的启用方式,配置如下:
[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <task:executor id="myexecutor" pool-size="5"  />  
  2. <task:annotation-driven executor="myexecutor"/>  
   以上就是两种定义的方式。

4. 基于@Async无返回值调用

    示例如下:

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Async  //标注使用  
  2. public void asyncMethodWithVoidReturnType() {  
  3.     System.out.println("Execute method asynchronously. "  
  4.       + Thread.currentThread().getName());  
  5. }  
  使用的方式非常简单,一个标注即可解决所有的问题。

5. 基于@Async返回值的调用

   示例如下:

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Async  
  2. public Future<String> asyncMethodWithReturnType() {  
  3.     System.out.println("Execute method asynchronously - "  
  4.       + Thread.currentThread().getName());  
  5.     try {  
  6.         Thread.sleep(5000);  
  7.         return new AsyncResult<String>("hello world !!!!");  
  8.     } catch (InterruptedException e) {  
  9.         //  
  10.     }  
  11.    
  12.     return null;  
  13. }  
   以上示例可以发现,返回的数据类型为Future类型,其为一个接口。具体的结果类型为AsyncResult,这个是需要注意的地方。

   调用返回结果的异步方法示例:

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void testAsyncAnnotationForMethodsWithReturnType()  
  2.    throws InterruptedException, ExecutionException {  
  3.     System.out.println("Invoking an asynchronous method. "  
  4.       + Thread.currentThread().getName());  
  5.     Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();  
  6.    
  7.     while (true) {  ///这里使用了循环判断,等待获取结果信息  
  8.         if (future.isDone()) {  //判断是否执行完毕  
  9.             System.out.println("Result from asynchronous process - " + future.get());  
  10.             break;  
  11.         }  
  12.         System.out.println("Continue doing something else. ");  
  13.         Thread.sleep(1000);  
  14.     }  
  15. }  
  分析: 这些获取异步方法的结果信息,是通过不停的检查Future的状态来获取当前的异步方法是否执行完毕来实现的。

6. 基于@Async调用中的异常处理机制

    在异步方法中,如果出现异常,对于调用者caller而言,是无法感知的。如果确实需要进行异常处理,则按照如下方法来进行处理:

    1.  自定义实现AsyncTaskExecutor的任务执行器

         在这里定义处理具体异常的逻辑和方式。

    2.  配置由自定义的TaskExecutor替代内置的任务执行器

    示例步骤1,自定义的TaskExecutor

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor {  
  2.     private AsyncTaskExecutor executor;  
  3.     public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {  
  4.         this.executor = executor;  
  5.      }  
  6.       ////用独立的线程来包装,@Async其本质就是如此  
  7.     public void execute(Runnable task) {       
  8.       executor.execute(createWrappedRunnable(task));  
  9.     }  
  10.     public void execute(Runnable task, long startTimeout) {  
  11.         /用独立的线程来包装,@Async其本质就是如此  
  12.        executor.execute(createWrappedRunnable(task), startTimeout);           
  13.     }   
  14.     public Future submit(Runnable task) { return executor.submit(createWrappedRunnable(task));  
  15.        //用独立的线程来包装,@Async其本质就是如此。  
  16.     }   
  17.     public Future submit(final Callable task) {  
  18.       //用独立的线程来包装,@Async其本质就是如此。  
  19.        return executor.submit(createCallable(task));   
  20.     }   
  21.       
  22.     private Callable createCallable(final Callable task) {   
  23.         return new Callable() {   
  24.             public T call() throws Exception {   
  25.                  try {   
  26.                      return task.call();   
  27.                  } catch (Exception ex) {   
  28.                      handle(ex);   
  29.                      throw ex;   
  30.                    }   
  31.                  }   
  32.         };   
  33.     }  
  34.   
  35.     private Runnable createWrappedRunnable(final Runnable task) {   
  36.          return new Runnable() {   
  37.              public void run() {   
  38.                  try {  
  39.                      task.run();   
  40.                   } catch (Exception ex) {   
  41.                      handle(ex);   
  42.                    }   
  43.             }  
  44.         };   
  45.     }   
  46.     private void handle(Exception ex) {  
  47.       //具体的异常逻辑处理的地方  
  48.       System.err.println("Error during @Async execution: " + ex);  
  49.     }  
  50. }  

 分析: 可以发现其是实现了AsyncTaskExecutor, 用独立的线程来执行具体的每个方法操作。在createCallable和createWrapperRunnable中,定义了异常的处理方式和机制。

handle()就是未来我们需要关注的异常处理的地方。

      配置文件中的内容:

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <task:annotation-driven executor="exceptionHandlingTaskExecutor" scheduler="defaultTaskScheduler" />  
  2. <bean id="exceptionHandlingTaskExecutor" class="nl.jborsje.blog.examples.ExceptionHandlingAsyncTaskExecutor">  
  3.     <constructor-arg ref="defaultTaskExecutor" />  
  4. </bean>  
  5. <task:executor id="defaultTaskExecutor" pool-size="5" />  
  6. <task:scheduler id="defaultTaskScheduler" pool-size="1" />  
  分析: 这里的配置使用自定义的taskExecutor来替代缺省的TaskExecutor。

7. @Async调用中的事务处理机制

    在@Async标注的方法,同时也适用了@Transactional进行了标注;在其调用数据库操作之时,将无法产生事务管理的控制,原因就在于其是基于异步处理的操作。

     那该如何给这些操作添加事务管理呢?可以将需要事务管理操作的方法放置到异步方法内部,在内部被调用的方法上添加@Transactional.

    例如:  方法A,使用了@Async/@Transactional来标注,但是无法产生事务控制的目的。

          方法B,使用了@Async来标注,  B中调用了C、D,C/D分别使用@Transactional做了标注,则可实现事务控制的目的。

8. 总结

     通过以上的描述,应该对@Async使用的方法和注意事项了。

转自http://blog.csdn.net/blueheart20/article/details/44648667

猜你喜欢

转载自ydlmlh.iteye.com/blog/2062788