当前位置: 移动技术网 > IT编程>开发语言>Java > Spring中@Async用法详解及简单实例

Spring中@Async用法详解及简单实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring中@async用法

引言: 在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配置的启用方式:

@configuration 
@enableasync 
public class springasyncconfig { ... } 

     基于xml配置文件的启用方式,配置如下:

<task:executor id="myexecutor" pool-size="5" /> 
<task:annotation-driven executor="myexecutor"/> 

   以上就是两种定义的方式。

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

    示例如下:

@async //标注使用 
public void asyncmethodwithvoidreturntype() { 
  system.out.println("execute method asynchronously. " 
   + thread.currentthread().getname()); 
} 

  使用的方式非常简单,一个标注即可解决所有的问题。

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

   示例如下:

@async 
public future<string> asyncmethodwithreturntype() { 
  system.out.println("execute method asynchronously - " 
   + thread.currentthread().getname()); 
  try { 
    thread.sleep(5000); 
    return new asyncresult<string>("hello world !!!!"); 
  } catch (interruptedexception e) { 
    // 
  } 
  
  return null; 
} 

   以上示例可以发现,返回的数据类型为future类型,其为一个接口。具体的结果类型为asyncresult,这个是需要注意的地方。

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

public void testasyncannotationformethodswithreturntype() 
  throws interruptedexception, executionexception { 
  system.out.println("invoking an asynchronous method. " 
   + thread.currentthread().getname()); 
  future<string> future = asyncannotationexample.asyncmethodwithreturntype(); 
  
  while (true) { ///这里使用了循环判断,等待获取结果信息 
    if (future.isdone()) { //判断是否执行完毕 
      system.out.println("result from asynchronous process - " + future.get()); 
      break; 
    } 
    system.out.println("continue doing something else. "); 
    thread.sleep(1000); 
  } 
} 

  分析: 这些获取异步方法的结果信息,是通过不停的检查future的状态来获取当前的异步方法是否执行完毕来实现的。

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

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

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

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

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

    示例步骤1,自定义的taskexecutor

public class exceptionhandlingasynctaskexecutor implements asynctaskexecutor { 
  private asynctaskexecutor executor; 
  public exceptionhandlingasynctaskexecutor(asynctaskexecutor executor) { 
    this.executor = executor; 
   } 
   ////用独立的线程来包装,@async其本质就是如此 
  public void execute(runnable task) {    
   executor.execute(createwrappedrunnable(task)); 
  } 
  public void execute(runnable task, long starttimeout) { 
    /用独立的线程来包装,@async其本质就是如此 
    executor.execute(createwrappedrunnable(task), starttimeout);      
  }  
  public future submit(runnable task) { return executor.submit(createwrappedrunnable(task)); 
    //用独立的线程来包装,@async其本质就是如此。 
  }  
  public future submit(final callable task) { 
   //用独立的线程来包装,@async其本质就是如此。 
    return executor.submit(createcallable(task));  
  }  
   
  private callable createcallable(final callable task) {  
    return new callable() {  
      public t call() throws exception {  
         try {  
           return task.call();  
         } catch (exception ex) {  
           handle(ex);  
           throw ex;  
          }  
         }  
    };  
  } 
 
  private runnable createwrappedrunnable(final runnable task) {  
     return new runnable() {  
       public void run() {  
         try { 
           task.run();  
         } catch (exception ex) {  
           handle(ex);  
          }  
      } 
    };  
  }  
  private void handle(exception ex) { 
   //具体的异常逻辑处理的地方 
   system.err.println("error during @async execution: " + ex); 
  } 
} 

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

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

      配置文件中的内容:

<task:annotation-driven executor="exceptionhandlingtaskexecutor" scheduler="defaulttaskscheduler" /> 
<bean id="exceptionhandlingtaskexecutor" class="nl.jborsje.blog.examples.exceptionhandlingasynctaskexecutor"> 
  <constructor-arg ref="defaulttaskexecutor" /> 
</bean> 
<task:executor id="defaulttaskexecutor" pool-size="5" /> 
<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使用的方法和注意事项了。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网