SpringBoot使用@Async注解实现异步调用
什么是@Async
被@Async标注的方法,称之为异步方法,会被独立的线程所执行,调用者无需等待它执行完毕,也可以执行其他操作。@Async标注在类上,表明类的所有方法都是异步方法
@Async的具体使用
1、在项目启动类上加上@EnableAsync注解,表明开启异步调用
2、自定义线程池
package com.example.task.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@EnableAsync
@Configuration
public class ExecutorConfig {
private static final int CORE_POOL_SIZE=Runtime.getRuntime().availableProcessors();
private static final int MAX_POOL_SIZE=2*CORE_POOL_SIZE;
private static final int KEEPALIVE_SECONDS=60;
private static final int QUERY_CAPACITY=128;
private static final int AVAIL_TERMINATION_MILLIS=60;
private static final String THREAD_NAME_PREFIX="TaskExecutor";
@Bean("executor")
public Executor executor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(CORE_POOL_SIZE);
//最大线程数
executor.setMaxPoolSize(MAX_POOL_SIZE);
//允许线程的空闲时间
executor.setKeepAliveSeconds(KEEPALIVE_SECONDS);
//缓冲队列
executor.setQueueCapacity(QUERY_CAPACITY);
//线程的前缀
executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
//设置线程中任务的等待时间
executor.setAwaitTerminationMillis(AVAIL_TERMINATION_MILLIS);
//线程对拒绝任务的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//线程关闭的时候等待所有任务都完成后再继续销毁其他的bean
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
3、编写异步线程方法
package com.example.task.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class ExecutorTaskService {
@Async("executor")
public Future<String> messages1(){
System.out.println("我是number one");
return new AsyncResult<>("");
}
@Async("executor")
public Future<String> messages2(){
System.out.println("我是number two");
return new AsyncResult<>("");
}
@Async("executor")
public Future<String> messages3(){
System.out.println("我是number three");
return new AsyncResult<>("");
}
}
4、编写控制类,调用异步方法
package com.example.task.controller;
import com.example.task.service.ExecutorTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExecutorController {
@Autowired
ExecutorTaskService executorTaskService;
@RequestMapping("/task")
public void getMessage(){
System.err.println("=====================");
executorTaskService.messages1();
executorTaskService.messages2();
executorTaskService.messages3();
}
}
5、运行程序,对getMessage()方法进行多次访问,得到的结果如下
会发现getMessage()方法内调用的三个异步方法不是按顺序输出的,证明异步调动生效
这里我是用的很简单的例子来说明@Async是如何使用的,理解用法即可
还没有评论,来说两句吧...