Spring中@Async用法总结

1、@controller 控制器(注入服务)

2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的)
@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
下面写这个是引入component的扫描组件

其中base-package为需要扫描的包(含所有子包)
1、@Service用于标注业务层组件
2、@Controller用于标注控制层组件(如struts中的action)
3、@Repository用于标注数据访问组件,即DAO组件.
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service public class UserServiceImpl implements UserService { }
@Repository public class UserDaoImpl implements UserDao { } getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“*”) 这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”)
@Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意): @PostConstruct public void init() { }

使用前
1.声明

@EnableAsync
@Component
@Lazy(false)
public class AsyncTask {
    private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class);
    @Autowired
    private AutoAllocateCaseJob autoAllocateCaseJob;
    @Autowired
    private ColService colService;
    public AsyncTask(){
        logger.info("task初始化");
    }
    @Async
    public void startAllocateCaseJob(){
        autoAllocateCaseJob.execute();
    }
    @Async
    public Future<ReminderUserDetailRtnModel> queryCurrentPayables(UserDetailReq userDetailReq){
        AsyncResult<ReminderUserDetailRtnModel> result=null;
        try{
        ReminderUserDetailRtnModel reminderUserDetailRtn = colService.queryReminderUserDetail(userDetailReq);
            result=new AsyncResult<ReminderUserDetailRtnModel>(reminderUserDetailRtn);
        }catch(Exception e){
            logger.error("错误",e);
        }
        return result;
    }
}

@Lazy(false)立即加载 @Lazy(true)延迟加载,用到才加载

2.在applicationContext.xml中加入到扫描包里面确保能扫描到

<context:component-scan base-package="com.vip.xfd.col.admin.async" />

3. 到相关的service里面用到的时候加入注解

@Autowired
    private AsyncTask asyncTask; 

4. @Configuration 注解的使用

下面是一个典型的Spring配置文件(application-config.xml):
Xml代码 
[xml] view plain copy
<beans>  
        <bean id="orderService" class="com.acme.OrderService"/>  
                <constructor-arg ref="orderRepository"/>  
        </bean>  
        <bean id="orderRepository" class="com.acme.OrderRepository"/>  
                <constructor-arg ref="dataSource"/>  
        </bean>  
</beans>  

然后你就可以像这样来使用是bean了:

java代码

[java] view plain copy
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");  
OrderService orderService = (OrderService) ctx.getBean("orderService");  
现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:

[java] view plain copy
@Configuration  
public class ApplicationConfig {  

        public @Bean OrderService orderService() {  
                return new OrderService(orderRepository());  
        }  

        public @Bean OrderRepository orderRepository() {  
                return new OrderRepository(dataSource());  
        }  

        public @Bean DataSource dataSource() {  
                // instantiate and return an new DataSource …  
        }  
}  
然后你就可以像这样来使用是bean了:

[java] view plain copy
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);  
OrderService orderService = ctx.getBean(OrderService.class);

5. @Async介绍

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

 如何在Spring中启用@Async

基于Java配置的启用方式:
@Configuration  
@EnableAsync  
public class SpringAsyncConfig { ... }  
 基于XML配置文件的启用方式,配置如下:
<task:executor id="myexecutor" pool-size="5"  />  
<task:annotation-driven executor="myexecutor"/>  

以上就是两种定义的方式。
5.1. 基于@Async无返回值调用

示例如下:
@Async  //标注使用  
public void asyncMethodWithVoidReturnType() {  
    System.out.println("Execute method asynchronously. "  
      + Thread.currentThread().getName());  
}  

使用的方式非常简单,一个标注即可解决所有的问题。
5.2 基于@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的状态来获取当前的异步方法是否执行完毕来实现的。
5.3. 基于@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。
5.4. @Async调用中的事务处理机制

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

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

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

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

猜你喜欢

转载自my.oschina.net/u/3800936/blog/1798133