SpringBoot中如何优雅的使用多线程

本文介绍了在SpringBoot应用中如何使用@Async注解实现异步方法,包括无返回值和有返回值的情况。通过配置ThreadPoolTaskExecutor线程池,可以优雅地处理多线程任务。当异步方法有返回值时,使用CompletableFuture进行组合和结果获取。文章还提到了@Async注解可能失效的场景,并强调了返回值限制。

本文带你快速了解@Async注解的用法,包括异步方法无返回值、有返回值,最后总结了@Async注解失效的几个坑。

在 SpringBoot 应用中,经常会遇到在一个接口中,同时做事情1,事情2,事情3,如果同步执行的话,则本次接口时间取决于事情1 2 3执行时间之和;如果三件事同时执行,则本次接口时间取决于事情1 2 3执行时间最长的那个,合理使用多线程,可以大大缩短接口时间。那么在 SpringBoot 应用中如何优雅的使用多线程呢?

Don't bb, show me code.

快速使用 

SpringBoot应用中需要添加@EnableAsync注解,来开启异步调用,一般还会配置一个线程池,异步的方法交给特定的线程池完成,如下:

@Configuration
@EnableAsync
public class AsyncConfiguration {

    @Bean("doSomethingExecutor")
    public Executor doSomethingExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数:线程池创建时候初始化的线程数
        executor.setCorePoolSize(10);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(20);
        // 缓冲队列:用来缓冲执行任务的队列
        executor.setQueueCapacity(500);
        // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("do-something-");
        // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

}

使用的方式非常简单,在需要异步的方法上加@Async注解 

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/open/something")
    public String something() {
        int count = 10;
        for (int i = 0; i < count; i++) {
            asyncService.doSomething("index = " + i);
        }
        return "success";
    }
}


@Slf4j
@Service
public class AsyncService {

    // 指定使用beanname为doSomethingExecutor的线程池
    @Async("doSomethingExecutor")
    public String doSomething(String message) {
        log.info("do something, message={}", message);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("do something error: ", e);
        }
        return message;
    }
}

访问:127.0.0.1:8080/open/something,日志如下 

2023-02-06 23:42:42.486  INFO 21168 --- [io-8200-exec-17] x.g.b.system.controller.AsyncController  : do something end, time 8 milliseconds
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-1] x.gits.boot.system.service.AsyncService  : do something, message=index = 0
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-5] x.gits.boot.system.service.AsyncService  : do something, message=index = 4
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-4] x.gits.boot.system.service.AsyncService  : do something, message=index = 3
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-6] x.gits.boot.system.service.AsyncService  : do something, message=index = 5
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-9] x.gits.boot.system.service.AsyncService  : do something, message=index = 8
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-8] x.gits.boot.system.service.AsyncService  : do something, message=index = 7
2023-02-06 23:42:42.488  INFO 21168 --- [do-something-10] x.gits.boot.system.service.AsyncService  : do something, message=index = 9
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-7] x.gits.boot.system.service.AsyncService  : do something, message=index = 6
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-2] x.gits.boot.system.service.AsyncService  : do something, message=index = 1
2023-02-06 23:42:42.488  INFO 21168 --- [ do-something-3] x.gits.boot.system.service.AsyncService  : do something, message=index = 2

由此可见已经达到异步执行的效果了,并且使用到了咱们配置的线程池。 

获取异步方法返回值 

当异步方法有返回值时,如何获取异步方法执行的返回结果呢?这时需要异步调用的方法带有返回值CompletableFuture。

CompletableFuture是对Feature的增强,Feature只能处理简单的异步任务,而CompletableFuture可以将多个异步任务进行复杂的组合。如下:

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @SneakyThrows
    @ApiOperation("异步 有返回值")
    @GetMapping("/open/somethings")
    public String somethings() {
        CompletableFuture<String> createOrder = asyncService.doSomething1("create order");
        CompletableFuture<String> reduceAccount = asyncService.doSomething2("reduce account");
        CompletableFuture<String> saveLog = asyncService.doSomething3("save log");

        // 等待所有任务都执行完
        CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join();
        // 获取每个任务的返回结果
        String result = createOrder.get() + reduceAccount.get() + saveLog.get();
        return result;
    }
}


@Slf4j
@Service
public class AsyncService {

    @Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething1(String message) throws InterruptedException {
        log.info("do something1: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("do something1: " + message);
    }

    @Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething2(String message) throws InterruptedException {
        log.info("do something2: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("; do something2: " + message);
    }

    @Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething3(String message) throws InterruptedException {
        log.info("do something3: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("; do something3: " + message);
    }
}

访问接口 

C:\Users\Administrator>curl -X GET "http://localhost:8080/open/something"  -H "accept: */*"
do something1: create order;
do something2: reduce account;
do something3: save log

控制台上关键日志如下: 

2023-02-06 00:27:42.238  INFO 5672 --- [ do-something-3] x.gits.boot.system.service.AsyncService  : do something3: save log
2023-02-06 00:27:42.238  INFO 5672 --- [ do-something-2] x.gits.boot.system.service.AsyncService  : do something2: reduce account
2023-02-06 00:27:42.238  INFO 5672 --- [ do-something-1] x.gits.boot.system.service.AsyncService  : do something1: create order

注意事项 

@Async注解会在以下几个场景失效,也就是说明明使用了@Async注解,但就没有走多线程。

  • 异步方法使用static关键词修饰;
  • 异步类不是一个Spring容器的bean(一般使用注解@Component@Service,并且能被Spring扫描到);
  • SpringBoot应用中没有添加@EnableAsync注解;
  • 在同一个类中,一个方法调用另外一个有@Async注解的方法,注解不会生效。原因是@Async注解的方法,是在代理类中执行的。

需要注意的是: 异步方法使用注解@Async的返回值只能为void或者Future及其子类,当返回结果为其他类型时,方法还是会异步执行,但是返回值都是null,部分源码如下:

AsyncExecutionInterceptor#invoke

通过上边几个示例,@Async实际还是通过Future或CompletableFuture来异步执行的,Spring又封装了一下,让我们使用的更方便。 


你在SpringBoot应用中如何使用多线程的呢不妨留言说说你遇到的坑

<think>我们要回答的是:在Spring Boot项目中如何使用Future进行多线程编程。 根据引用[2][3][4][5],我们知道Spring Boot中通常使用线程池来管理多线程任务,并且通过@EnableAsync开启异步支持,然后使用@Async注解来标记异步方法。 而Future是Java并发编程中用于获取异步计算结果的接口。在Spring Boot中,我们可以通过返回Future类型的方法来实现异步调用并获取结果。 步骤: 1. 配置线程池(如引用[4][5]所示),使用@Configuration和@EnableAsync,并定义一个Executor Bean。 2. 在启动类上添加@EnableAsync(如引用[5]所示)。 3. 编写异步方法,返回类型为Future<T>(可以是Future的实现类,比如AsyncResult)。 下面我们给出一个具体的示例: 首先,配置线程池(可以放在任何配置类中): ```java @Configuration @EnableAsync public class AsyncConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(500); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("Async-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } } ``` 然后,在一个Service中编写异步方法,返回Future: ```java @Service public class MyService { @Async("taskExecutor") public Future<String> doSomethingLong() { // 模拟长时间任务 try { Thread.sleep(5000); // 休眠5秒 return new AsyncResult<>("Task Completed"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new AsyncResult<>("Task Interrupted"); } } } ``` 在Controller中调用: ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/start-task") public String startTask() throws Exception { Future<String> future = myService.doSomethingLong(); // 这里可以继续处理其他任务 // 如果需要等待结果,可以调用future.get(),但这会阻塞直到返回结果 // 为了非阻塞,通常我们会使用轮询或者回调,但这里简单示例阻塞获取 return future.get(); } } ``` 注意: - @Async注解的方法必须是public方法,并且不能在同一个类中调用(因为代理问题)。 - Future.get()方法会阻塞直到任务完成。为了避免阻塞,我们可以使用Future.isDone()来检查任务是否完成,或者使用带超时的get方法。 另外,Spring还提供了AsyncTaskExecutor和CompletableFuture(从Spring 4开始支持)等更现代化的异步编程方式,但这里我们主要讲Future。 关于Future的更多使用方式,比如取消任务、设置超时等: ```java // 取消任务 future.cancel(true); // 带超时的获取结果 try { String result = future.get(2, TimeUnit.SECONDS); } catch (TimeoutException e) { // 处理超时 } ``` 引用[4]中提到,异步方法可以使用@Async,并返回Future类型。上面的示例就是基于这个原理。 总结: 在Spring Boot使用Future进行多线程编程的步骤: 1. 配置线程池使用@EnableAsync和定义Executor Bean)。 2. 在异步方法上使用@Async,并返回Future类型。 3. 在调用处获取Future对象,并根据需要处理结果(阻塞获取、带超时获取等)。 注意线程安全问题:确保异步方法中使用的资源是线程安全的,或者使用适当的同步机制。 根据引用[1],多线程编程中线程安全是一个重要问题,因此在实际开发中需要注意。 以上内容参考了引用[1][2][3][4][5],特别是引用[4]和[5]提供了配置和基础使用的示例。 相关问题: 1. 在Spring Boot中如何配置多个线程池? 2. 除了Future,Spring Boot中还有哪些处理异步调用结果的方式? 3. 如何避免在Spring Boot多线程编程中出现线程安全问题? 4. 在Spring Boot中如何优雅地关闭线程池? </think>### Spring Boot中Future的多线程使用方法 在Spring Boot项目中,`Future`接口用于获取异步任务执行结果,结合线程池和`@Async`注解可实现高效的多线程编程。以下是具体实现步骤: #### 1. 配置线程池(必需) ```java @Configuration @EnableAsync public class AsyncConfig { @Bean("taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); // 核心线程数 executor.setMaxPoolSize(20); // 最大线程数 executor.setQueueCapacity(500); // 队列容量 executor.setKeepAliveSeconds(60); // 线程空闲时间 executor.setThreadNamePrefix("async-"); // 线程名前缀 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略 executor.initialize(); return executor; } } ``` > 要点:需添加`@EnableAsync`启用异步支持[^4][^5]。 #### 2. 创建异步服务 ```java @Service public class AsyncService { @Async("taskExecutor") // 指定线程池 public Future<String> asyncTaskWithFuture(int taskId) { try { Thread.sleep(2000); // 模拟耗时操作 return new AsyncResult<>("任务[" + taskId + "]完成"); } catch (InterruptedException e) { return new AsyncResult<>("任务失败"); } } } ``` > 说明: > - 返回类型必须为`Future<T>`或`CompletableFuture<T>` > - `AsyncResult`是Spring的`Future`实现类 #### 3. 调用异步方法并获取结果 ```java @RestController public class TaskController { @Autowired private AsyncService asyncService; @GetMapping("/run-tasks") public String runTasks() throws Exception { Future<String> task1 = asyncService.asyncTaskWithFuture(1); Future<String> task2 = asyncService.asyncTaskWithFuture(2); // 阻塞获取结果(实际应用中建议使用超时机制) String result1 = task1.get(); String result2 = task2.get(); return result1 + " | " + result2; } } ``` #### 关键操作说明 | **操作** | **代码示例** | **作用** | |-----------------------|--------------------------------------|-----------------------------| | 提交任务 | `Future<String> future = asyncService.asyncTaskWithFuture(id)` | 提交异步任务到线程池 | | 阻塞获取结果 | `future.get()` | 等待任务完成并返回结果 | | 带超时的获取 | `future.get(5, TimeUnit.SECONDS)` | 避免无限期阻塞 | | 检查任务状态 | `future.isDone()` | 判断任务是否完成 | | 取消任务 | `future.cancel(true)` | 尝试中断正在执行的任务 | > **注意事项**: > 1. 避免在**同一类内**调用`@Async`方法(代理失效问题) > 2. 建议使用`future.get(timeout, unit)`防止线程永久阻塞 > 3. 线程池参数需根据实际负载调整[^2][^4] > 4. 异步方法需处理所有异常,否则错误会被吞没 #### 完整执行流程 ```mermaid graph TD A[控制器调用asyncTaskWithFuture] --> B[Spring代理将任务提交到线程池] B --> C[线程池分配线程执行任务] C --> D[任务执行完成返回AsyncResult] D --> E[通过Future.get获取结果] ``` ### 典型应用场景 1. 批量数据处理(如Excel导入) 2. 第三方API并行调用 3. 耗时操作解耦(邮件发送、日志归档) 4. 微服务中聚合多个服务响应 > 通过合理使用`Future`,可将平均响应时间降低50%~70%(取决于任务并行度)[^1][^2]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值