SpringBoot学习9.0-异步线程池

概要

开发要点:

  • 实现AsyncConfigurer接口
  • @EnableAsync开启异步
  • @Async标注希望异步执行的方法

1.异步线程池配置类

通过实现AsyncConfigurer接口配置线程池。

@EnableAsync开启异步。

import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/** 异步线程池配置类 */
@Configuration
@EnableAsync // 开启spring异步
public class AsyncThreadPoolConfig implements AsyncConfigurer {
	@Override
	public Executor getAsyncExecutor() {
		// 定义线程池
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		// 核心线程数=启用线程的个数
		threadPoolTaskExecutor.setCorePoolSize(10);
		// 线程池最大线程数
		threadPoolTaskExecutor.setMaxPoolSize(300);
		// 线程队列最大线程数
		threadPoolTaskExecutor.setQueueCapacity(2000);
		// 初始化线程池
		threadPoolTaskExecutor.initialize();
		return threadPoolTaskExecutor;
	}
	// 异常处理方法
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		System.out.println("异常了......");
		return null;
	}
}

2.异步方法

@Async标注的方法被调用将使用异步线程池来执行。

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncServiceImpl{
	@Async // 使用异步调用
	public String asynctest(String threadName) {
		System.out.println(threadName+ " —> " + Thread.currentThread().getName());
		return null;
	}
}

3.测试

多次调用异步方法。

@Controller
@RequestMapping(path="/asyncmvc")
public class AsyncController {
	@Autowired
	private AsyncServiceImpl asyncService;
	@RequestMapping(value="/ma1")
	public String am1(ModelAndView mav){
		int num = 1;
		while (num <= 15) {
			asyncService.asynctest(Thread.currentThread().getName()+ "");
			num++;
		}
		return "asyncmvc/ma1";
	}
}

请求http://localhost:8081/asyncmvc/ma1,输出日志:

http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-1
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-5
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-9
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-2
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-10
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-8
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-4
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-3
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-6
http-nio-8081-exec-4 —> ThreadPoolTaskExecutor-7

可见,同一线程调用,异步方法使用不同的线程来执行。

 

github:https://github.com/zhangyangfei/SpringBootLearn.git中的springTech工程。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值