利用 Spring 的 @Async 异步处理改善 web 应用中耗时操作的用户体验

305 阅读1分钟

总结步骤:

1.在启动类或者 Control 类加上 @EnableAsync 注解,@Async 所修饰的函数不要定义为 static 类型,这样异步调用不会生效。(好像这一步不是必须的)

2.创建自定义的 Bean

@Configuration
@EnableAsync
public class UpdateConfig {
    @Bean("update")   // 使用的时候需要指定名字 update
    public Executor updateESExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(1);
        // 设置最大线程数
        executor.setMaxPoolSize(1);
        // 设置队列容量
        executor.setQueueCapacity(0);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(120);
        // 设置默认线程名称
        executor.setThreadNamePrefix("updateES-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
    
    @Bean("other")   // 可以使用其他名字配置其他的线程池 update
    public Executor otherExecutor() {
    	...
    }
}

3.在 service 实现耗时接口的方法上面加上注解 @Async("update") ,表示用到这个名为 update 的线程池。

4.调用耗时接口检验是否能立刻返回,且能在后台执行。

转载记录:

https://www.cnblogs.com/yjmyzz/p/how-to-use-Async-annotation-in-spring-mvc.html
https://blog.csdn.net/qq_39186755/article/details/100548808