当前位置: 首页 > news >正文

springboot异步多线程的实现

1、配置线程池相关参数

package com.xxx.test.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;@Slf4j
@Configuration
@EnableAsync(proxyTargetClass = true)
public class AsyncConfig implements AsyncConfigurer {@Bean("asyncExecutor")public Executor asyncExecutor(){ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(3);executor.setMaxPoolSize(10);executor.setQueueCapacity(Integer.MAX_VALUE);executor.setThreadNamePrefix("common-async-");executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());executor.initialize();return executor;}/*** 只能捕获无返回值的异步方法,有返回值的被主线程处理*/@Overridepublic AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return new CustomAsyncExceptionHandler();}/**** 处理异步方法中未捕获的异常*/class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {@Overridepublic void handleUncaughtException(Throwable throwable, Method method, Object... obj) {log.info("Exception message - {}", throwable.getMessage());log.info("Method name - {}", method.getName());log.info("Parameter values - {}", Arrays.toString(obj));if (throwable instanceof Exception) {Exception exception = (Exception) throwable;log.info("exception:{}", exception.getMessage());}throwable.printStackTrace();}}}

2、编写异步服务

package com.xxx.xxx.service.impl;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;import java.util.concurrent.Future;@Slf4j
@Service
public class AsyncService {@Async("asyncExecutor")public void task1() throws Exception {log.info("task1开始执行");Thread.sleep(3000);log.info("task1执行结束");throw new RuntimeException("出现异常");}//todo 只能捕获无返回值的异步方法,有返回值的被主线程处理,还是要在主线程判断代码@Async("asyncExecutor")public Future<String> task2() throws Exception {log.info("task2开始执行");Thread.sleep(3000);log.info("task2执行结束");throw new RuntimeException("出现异常");// return new AsyncResult<String>("task2 success");}@Async("asyncExecutor")public Future<Integer> task3(Integer num) throws Exception {log.info("task3开始执行,num:{}", num);//Thread.sleep(3000);log.info("task3执行结束,num:{}", num);return new AsyncResult<Integer>(num);}@Async("asyncExecutor")public Future<String> task4() throws Exception {log.info("task4开始执行");Thread.sleep(3000);log.info("task4执行结束");return new AsyncResult<String>("task4 success");}}

3、controller层服务调用

 @RequestMapping(value = "/getTest", method = RequestMethod.GET)public BasicResult getTest(Integer num) throws Exception {BasicResult<String> basicResult = new BasicResult<>();log.info("{} 接受到请求:num={}", Thread.currentThread().getName(), num);//TimeUnit.HOURS.sleep(1);asyncService.task1();asyncService.task2();Future<Integer> integerFuture = asyncService.task3(num);basicResult.setSingleResult(integerFuture.get().toString());return basicResult;}

4、如果启用异步线程池,需要在启动类加上  @EnableAsync(proxyTargetClass = true) 注解

http://www.lryc.cn/news/108054.html

相关文章:

  • 测试相关基础概念与常见开发模型
  • MySQL安装详细教程!!!
  • 前端下载文化部几种方法(excel,zip,html,markdown、图片等等)和导出 zip 压缩包
  • 铠甲网络面试(部分)
  • elasticsearch 将时间类型为时间戳保存格式的时间字段格式化返回
  • 淘宝商品列表怎么通过接口形式导出?
  • TWS真无线蓝牙耳机哪家好?六款口碑好的TWS真无线蓝牙耳机分享
  • 解决Win11右键菜单问题
  • 开源元数据管理平台Datahub最新版本0.10.5——安装部署手册(附离线安装包)
  • 归并排序——“数据结构与算法”
  • C语言笔试题训练【第一天】
  • 计算语言模型计算每秒钟生成的token数量it/s
  • Clickhouse调研
  • 02.Redis实现添加缓存功能
  • 【1.2】Java微服务:SpringCloud概论
  • 右键文件夹 ------- 打开 vscode的方法
  • 小程序原生实现左右锚点联动
  • STM32 低功耗-睡眠模式
  • IDEA用Gradle构建项目时,lombok插件无效的解决办法
  • 基于方向编码的模板匹配算法matlab仿真
  • shell centos 7 一键部署 KVM软件脚本
  • 64 # 实现一个 http-server
  • HCIP作业3
  • 【测试学习三】软件测试的生命周期 BUG的相关知识
  • git rebase 的坑儿
  • SSM(Vue3+ElementPlus+Axios+SSM前后端分离)【四】
  • iPhone 8 Plus透明屏应用范围详解
  • 【前端面试手撕题】instanceof、Array.map、Array.filter、Array.reduce、_objectCreate
  • 8.物联网操作系统之事件标志组
  • [腾讯云Cloud Studio实战训练营]无门槛使用GPT+Cloud Studio辅助编程完成Excel自动工资结算