源码资源网 发表于 2024-10-8 13:23:35

在Spring Boot中配置自定义线程池并实现异步方法返回值

在Spring Boot中配置自定义线程池并实现异步方法返回值
在Spring Boot中配置自定义线程池并实现异步方法返回值,可以通过以下步骤完成。我们将使用 `@Async` 注解,并结合 `Future` 或 `CompletableFuture` 来实现异步返回值。
### 1. 添加依赖
确保在 `pom.xml` 中添加Spring Boot的依赖(如果你使用的是Maven):
xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

### 2. 启用异步支持
在你的主应用程序类或者配置类上添加 `@EnableAsync` 注解,以启用异步支持:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class AsyncApplication {
    public static void main(String[] args) {
      SpringApplication.run(AsyncApplication.class, args);
    }
}

### 3. 配置自定义线程池
创建一个配置类来定义自定义线程池:
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 AsyncConfig {
   @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(5); // 核心线程数
      executor.setMaxPoolSize(10); // 最大线程数
      executor.setQueueCapacity(25); // 队列容量
      executor.setThreadNamePrefix("Async-"); // 线程名称前缀
      executor.initialize();
      return executor;
    }
}或者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;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(5); // 核心线程数
      executor.setMaxPoolSize(10); // 最大线程数
      executor.setQueueCapacity(25); // 队列容量
      executor.setThreadNamePrefix("Async-"); // 线程名称前缀
         // 设置拒绝执行处理器
      executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // 这里可以自定义拒绝策略
                System.out.println("任务被拒绝: " + r.toString());
            }
      });
         executor.initialize();
      return executor;
    }
}

### 4. 创建异步服务
创建一个服务类,并在需要异步执行的方法上添加 `@Async` 注解,返回 `CompletableFuture` :
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
@Service
public class AsyncService {
   @Async("taskExecutor") // 指定使用自定义线程池
    public CompletableFuture<String> asyncMethod() {
      try {
            // 模拟耗时操作
            Thread.sleep(3000);
            return CompletableFuture.completedFuture("异步方法执行完成");
      } catch (InterruptedException e) {
            return CompletableFuture.completedFuture("执行失败");
      }
    }
}

### 5. 调用异步方法
在控制器中调用异步服务的方法,并处理返回值:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@RestController
public class AsyncController {
   @Autowired
    private AsyncService asyncService;
   @GetMapping("/startAsync")
    public CompletableFuture<String> startAsync() {
      return asyncService.asyncMethod();
    }
}

### 6. 运行应用
启动你的Spring Boot应用程序,并访问 `/startAsync` 端点。你会看到异步方法将在后台运行,并且返回值会在完成后返回。
### 注意事项
- **线程池配置**:可以根据实际需求调整线程池的核心线程数、最大线程数和队列容量。
- **异常处理**:在异步方法中发生的异常会被捕获并返回,可以在调用处处理这些异常。
- **@Async注解**:确保在Spring管理的bean中使用,并且可以指定使用哪个线程池。
这样,你就可以在Spring Boot中使用自定义线程池配置和异步返回值的功能了!


页: [1]
查看完整版本: 在Spring Boot中配置自定义线程池并实现异步方法返回值

免责声明:
1、本站提供的所有资源仅供参考学习使用,版权归原著所有,禁止下载本站资源参与商业和非法行为,请在24小时之内自行删除!
2、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,请勿任何商业目的与商业用途。
3、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。
4、论坛的所有内容都不保证其准确性,完整性,有效性,由于源码具有复制性,一经售出,概不退换。阅读本站内容因误导等因素而造成的损失本站不承担连带责任。
5、用户使用本网站必须遵守适用的法律法规,对于用户违法使用本站非法运营而引起的一切责任,由用户自行承担
6、本站所有资源来自互联网转载,版权归原著所有,用户访问和使用本站的条件是必须接受本站“免责声明”,如果不遵守,请勿访问或使用本网站
7、本站使用者因为违反本声明的规定而触犯中华人民共和国法律的,一切后果自己负责,本站不承担任何责任。
8、凡以任何方式登陆本网站或直接、间接使用本网站资料者,视为自愿接受本网站声明的约束。
9、本站以《2013 中华人民共和国计算机软件保护条例》第二章 “软件著作权” 第十七条为原则:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。若有学员需要商用本站资源,请务必联系版权方购买正版授权!
10、本网站如无意中侵犯了某个企业或个人的知识产权,请来信【站长信箱312337667@qq.com】告之,本站将立即删除。
郑重声明:
本站所有资源仅供用户本地电脑学习源代码的内含设计思想和原理,禁止任何其他用途!
本站所有资源、教程来自互联网转载,仅供学习交流,不得商业运营资源,不确保资源完整性,图片和资源仅供参考,不提供任何技术服务。
本站资源仅供本地编辑研究学习参考,禁止未经资源商正版授权参与任何商业行为,违法行为!如需商业请购买各资源商正版授权
本站仅收集资源,提供用户自学研究使用,本站不存在私自接受协助用户架设游戏或资源,非法运营资源行为。