前言
在Spring Framework中分别使用TaskExecutor和TaskScheduler接口提供异步执行和任务调度的抽象。
TaskExecutor主要用来创建线程池用来管理异步定时任务开启的线程,
TaskScheduler用于创建定时任务。
异步线程池
当我们想后台程序在生产过程中产生一些日志同时不影响我们主要功能的执行,我们并不需要看这个日志,只是要产生日志而已。
异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕。
Spring中存在一个AsyncConfigurer接口,它是一个可以配置异步线程池的接口
- getAsyncExecutor()方法返回一个自定义线程池,开启异步时,线程池就会提供空闲线程来执行异步任务。
- getAsyncUncaughtExceptionHandler()是一个异步异常处理器
- 使用的时候配置类实现AsyncConfigurer接口,实现getAsyncExecutor方法返回的线程池,这样Spring就会将使用这个线程池作为其异步调用的线程。
- @EnableAsync标注配置文件,Spring就会开启异步可用,可用使用注解@Async驱动Spring使用异步调用
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(8); //核心线程数
taskExecutor.setMaxPoolSize(16); //最大线程数
taskExecutor.setQueueCapacity(50); //阻塞队列大小
taskExecutor.initialize(); //初始化
return taskExecutor;
}
}
当我们的方法使用@Async驱动Spring使用异步,使用@Async后就会通过线程池的空闲线程去运行该方法。
public interface AsyncService {
public void getLog();
}
import org.springframework.scheduling.annotation.Async;
@Service
public class AsyncServiceImpl implements AsyncService{
@Override
@Async
public void getLog() {
//生成日志
//存储日志
}
}
import com.cncodehub.common.lang.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/page")
public Result page(){
//各种操作
asyncService.getLog();