欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 多线程 中 @Async 和 ThreadPoolTaskExecutor 的使用

程序员文章站 2022-08-29 20:54:20
配置线程池,实现AsyncConfigurer接口getAsyncExecutor 设置线程池getAsyncUncaughtExceptionHandler 异常日志处理import lombok.extern.slf4j.Slf4j;import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;import org.springframework.context.annotation.Configuration...

配置线程池,实现AsyncConfigurer接口

getAsyncExecutor 设置线程池

getAsyncUncaughtExceptionHandler 异常日志处理

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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.util.concurrent.Executor;

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        // 自定义线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(20);
        // 最大线程数
        taskExecutor.setMaxPoolSize(40);
        // 线程队列最大线程数
        taskExecutor.setQueueCapacity(1000);
        taskExecutor.setKeepAliveSeconds(999999999);
        taskExecutor.setRejectedExecutionHandler(new RejectedExecutionHandlerImpl());
        // 初始化线程池
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error("Error Occurs in async method:{}", ex.getMessage());
        };
    }

}

ThreadPoolTaskExecutor 底层调用的是jdk的ThreadPoolExecutor
SpringBoot 多线程 中 @Async 和 ThreadPoolTaskExecutor 的使用

b()方法 模拟异步线程返回值Future

c()方法 模拟异步线程异常处理


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author hzy
 * @Date 2020/7/15 20:12
 */
@RestController
@RequestMapping("/air")
public class AirController {

    @Autowired
    A a;

    @RequestMapping("/test")
    public void test() throws Exception {
        a.a();
        Future<String> future = a.b();
        while (true) {  //等待获取结果信息
            if (future.isDone()) {  //判断是否执行完毕
                System.out.println("Result from b - " + future.get());
                break;
            }
            System.out.println("------------continue");
            Thread.sleep(1000);
        }
        System.out.println("-------模拟异常处理");
        a.c();
    }


}

@Component
class A{

    @Async
    public void a() throws InterruptedException {
        System.out.println("Execute method - a " + Thread.currentThread().getName());
        Thread.sleep(1000);
        System.out.println("a方法结束");
    }

    @Async
    public Future<String> b() throws InterruptedException {
        System.out.println("Execute method - b " + Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println("b方法结束");
        return new AsyncResult<String>("hello world !!!!");
    }

    @Async
    public void c() throws Exception {
        System.out.println("Execute method - c " + Thread.currentThread().getName());
        throw new Exception("抛出异常");
    }
}

本文地址:https://blog.csdn.net/weixin_40760239/article/details/107388335

相关标签: SpringBoot java