您的位置:首页 > 编程语言 > Java开发

@EnableAsync和@Async开始异步任务支持

2017-07-28 17:37 357 查看
Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor.在开发中实现异步任务,我们可以在配置类中添加@EnableAsync开始对异步任务的支持,并在相应的方法中使用@Async注解来声明一个异步任务。

配置类

package com.xingguo.logistics.controller;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@ComponentScan({"com.xingguo.logistics.service.aspect","com.xingguo.logistics.service.event"})
//开始异步支持
@EnableAsync
public class AopConfig implements AsyncConfigurer{

@Override
public Executor getAsyncExecutor() {
//线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}

}


任务执行service类

package com.xingguo.logistics.service.aspect;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestService2 {

//声明异步任务
@Async
public void executeAsyncTask(Integer i){
System.out.println("执行异步任务:"+i);
}

@Async
public void executeAsyncTask2(Integer i){
System.out.println("执行异步任务2:"+i);
}

}


测试类

package com.xingguo.logistics.controller;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.xingguo.logistics.service.aspect.TestService2;

public class TestController {

public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);

TestService2 testService2 = context.getBean(TestService2.class);
for(int i = 0; i<10; i++){
testService2.executeAsyncTask(i);
testService2.executeAsyncTask2(i);
}
context.close();

}
}


测试结果如下:



执行结果可以看出,并没有按照顺序来执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息