springboot配置线程池-高并发场景

 

1.编写配置文件

package com.hbedu.search.hbsearch.utils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

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.ThreadPoolExecutor;


@Configuration

@EnableAsync

public class ExecutorConfig {



    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);


    @Bean

    public Executor asyncServiceExecutor() {

        logger.info("start asyncServiceExecutor");

        //ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();

        //配置核心线程数

        executo
  • 12
    点赞
  • 106
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
在Spring Boot中,我们可以使用@Async注解来异步执行方法。但是默认情况下,Spring Boot使用的是SimpleAsyncTaskExecutor,它是一个单线程的线程池,不能满足高并发场景的需求。因此,我们需要自定义线程池来满足不同的需求。 下面是自定义线程池的步骤: 1. 创建自定义线程池配置类 ```java @Configuration public class ThreadPoolConfig { @Bean("myThreadPool") public Executor myThreadPool(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 线程池核心线程数 executor.setCorePoolSize(10); // 线程池最大线程数 executor.setMaxPoolSize(20); // 队列容量 executor.setQueueCapacity(100); // 线程池维护线程所允许的空闲时间 executor.setKeepAliveSeconds(60); // 线程池的前缀名 executor.setThreadNamePrefix("myThreadPool-"); // 拒绝策略,当线程池满了并且队列也满了,新任务会被拒绝 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 初始化线程池 executor.initialize(); return executor; } } ``` 2. 在需要异步执行的方法上添加@Async注解,并指定使用的线程池 ```java @Service public class MyService { @Async("myThreadPool") public void asyncMethod(){ // 异步执行的方法体 } } ``` 3. 测试异步执行方法的效果 ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/async") public String async(){ myService.asyncMethod(); return "异步执行中..."; } } ``` 通过以上步骤,我们就可以自定义线程池来异步执行方法了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

格赚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值