在项目中有很多地方需要实现异步,@Async是一种比较简单的实现方式。
一、通过线程池配置
1、初始化线程池
@EnableAsync
@Configuration
@PropertySource("classpath:conf/core_thread.properties")
public class TaskPoolConfig {
@Value("${core.pool.size}")
private Integer corePooleSize;
@Value("${max.pool.size}")
private Integer maxPooleSize;
@Value("${queue.capacity}")
private Integer queueCapacity;
@Value("${alive.time}")
private Integer aliveTime;
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePooleSize);
executor.setMaxPoolSize(maxPooleSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(aliveTime);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
2、设置配置线程的配置
core.pool.size=10
max.pool.size=10
queue.capacity=200
alive.time=60
3、配置异步方法
@Component
public class AsyncTask {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Async("taskExecutor")
public void doTaskOne(String aa) throws Exception {
System.out.println("开始做任务一"+formatter.format(LocalDateTime.now())+aa);
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"+formatter.format(LocalDateTime.now())+aa);
}
}
4、将异步方法类注入方法,调用注入异步类的中异步方法
@Autowired
private AsyncTask asyncTask;
@Autowired
private OrderService orderService;
@RequestMapping("/page")
@AnnDemo(value = "page")
public List<Province> findPage(@RequestParam("username") String username) throws Exception {
asyncTask.doTaskOne("eee");
System.out.println("sdfffffff+"+formatter.format(LocalDateTime.now()));
List<Province> listPage=orderService.getProvinces();
System.out.println("sdfffffffkkkkk+"+formatter.format(LocalDateTime.now()));
return listPage;
}
查看执行结果
开始做任务一2019-09-19 21:38:35eee
sdfffffff+2019-09-19 21:38:35
2019-09-19 21:38:35.733 INFO 38688 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-19 21:38:36.068 INFO 38688 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
sdfffffffkkkkk+2019-09-19 21:38:36
完成任务一,耗时:5000毫秒2019-09-19 21:38:40eee
二、不用配置线程池的方式
1、配置异步方法
@Component
public class AsyncTask {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Async
public void doTaskOne(String aa) throws Exception {
System.out.println("开始做任务一"+formatter.format(LocalDateTime.now())+aa);
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"+formatter.format(LocalDateTime.now())+aa);
}
}
2、将异步方法类注入方法,调用注入异步类的中异步方法
@RequestMapping("/page")
@AnnDemo(value = "page")
public List<Province> findPage(@RequestParam("username") String username) throws Exception {
asyncTask.doTaskOne("eee");
System.out.println("sdfffffff+"+formatter.format(LocalDateTime.now()));
List<Province> listPage=orderService.getProvinces();
System.out.println("sdfffffffkkkkk+"+formatter.format(LocalDateTime.now()));
return listPage;
}
查看执行结果
sdfffffff+2019-09-19 22:00:35
开始做任务一2019-09-19 22:00:35eee
2019-09-19 22:00:35.989 INFO 34372 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-19 22:00:36.293 INFO 34372 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
sdfffffffkkkkk+2019-09-19 22:00:36
完成任务一,耗时:5001毫秒2019-09-19 22:00:40eee