springboot-异步使用
- 创建配置类,开启异步和创建线程
package com.chulx.demo1.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;
@Configuration
@EnableAsync
public class MyAsyncConfig {
/**
* 自定义线程池
*/
@Bean("taskExecutor")
public Executor taskExecutor() {
// 返回可用处理器的Java虚拟机的数量 12
int i = Runtime.getRuntime().availableProcessors();
System.out.println("系统最大线程数 :" + i);
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程池大小
executor.setCorePoolSize(16);
// 最大线程数
executor.setMaxPoolSize(20);
// 配置队列容量,默认值为Integer.MAX_VALUE
executor.setQueueCapacity(99999);
// 活跃时间
executor.setKeepAliveSeconds(60);
// 线程名字前缀
executor.setThreadNamePrefix("asyncServiceExecutor -");
// 设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
executor.setAwaitTerminationSeconds(60);
// 等待所有的任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
- 创建异步服务
package com.chulx.demo1.asyncService; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class MyAsyncService { @Async("taskExecutor") public void executeAsyncTask() throws InterruptedException { Thread.currentThread().sleep(5000); System.out.println("执行异步任务:" + Thread.currentThread().getName()); } }
- 同步服务调用异步服务
package com.chulx.demo1.service.impl; import com.chulx.demo1.asyncService.MyAsyncService; import com.chulx.demo1.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AsyncImplService implements AsyncService { @Autowired private MyAsyncService myAsyncService; @Override public void doSomething() throws InterruptedException { System.out.println("this is sync service"); myAsyncService.executeAsyncTask(); } }
- 控制器调用
@RestController @RequestMapping("async") @RequiredArgsConstructor public class MyAsyncController { private final AsyncService asyncService; @RequestMapping("test") public String test() throws InterruptedException { System.out.println("test"); asyncService.doSomething(); System.out.println("test2"); return "test"; } }
效果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?