SpringBoot异步执行方法
程序员文章站
2022-07-15 14:56:23
...
SpringBoot中使用@Async注解标记的方法,会在调用方法的当前线程之外的独立线程中执行。
Spring使用@Async注解实现异步任务:
- application类上加@EnableAsync注解:
@EnableAsync
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
- application同级目录下添加配置类(也可不配,方法上直接加@Async注解即可):
package com.h3c.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步任务线程池配置类
*
* @Description: 异步任务线程池配置类
*/
@Configuration
public class TaskPoolConfig {
@Bean("testTaskExecutor")
public Executor testTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("testTaskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
- 需要异步的方法或类上添加@Async注解:
@Async("testTaskExecutor")
public void testAsync(){
return;
}
上一篇: Spring Bean方法的异步执行
下一篇: vue两个异步方法顺序执行
推荐阅读
-
java 线程同步方法执行与唤醒实例
-
Mybaits 源码解析 (六)----- 全网最详细:Select 语句的执行过程分析(上篇)(Mapper方法是如何调用到XML中的SQL的?)
-
C#中for循环、while循环循环执行的方法
-
Python使用Selenium爬取淘宝异步加载的数据方法
-
Springboot apollo原理及使用方法详解
-
idea新建springboot项目的方法
-
Yii框架在页面输出执行sql语句以方便调试的实现方法
-
浅谈个人对客户端JavaScript同步、异步、执行顺序等概念的理解
-
C#实现异步连接Sql Server数据库的方法
-
springboot中jsp引用静态资源css,js的实现方法