springboot 多线程配置及使用

一、配置

(1)配置文件

在application中或者nacos中配置线程池参数,如下:

#线程池配置
task:
  pool:
    corePoolSize: 100
    maxPoolSize: 200
    keepAliveSeconds: 300
    queueCapacity: 50

(2)配置文件数据映射

/**
 * 线程池配置属性类
 */
@Data
@Component
@ConfigurationProperties(prefix = "task.pool")
public class TaskThreadPoolConfig {

    /**
     * 核心线程数
     */
    private int corePoolSize;

    /**
     * 最大线程数
     */
    private int maxPoolSize;

    /**
     * 线程空闲时间
     */
    private int keepAliveSeconds;

    /**
     * 任务队列容量(阻塞队列)
     */
    private int queueCapacity;
}

(3)config

/**
 * 重写默认线程池配置
 * @author YuXD
 */
@Slf4j
@Configuration
@EnableAsync
public class OverrideDefaultThreadPoolConfig implements AsyncConfigurer {

    @Autowired
    private TaskThreadPoolConfig taskThreadPoolConfig;

    @Override
	@Bean("taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(taskThreadPoolConfig.getCorePoolSize());
        //最大线程数
        executor.setMaxPoolSize(taskThreadPoolConfig.getMaxPoolSize());
        //队列容量
        executor.setQueueCapacity(taskThreadPoolConfig.getQueueCapacity());
        //活跃时间
        executor.setKeepAliveSeconds(taskThreadPoolConfig.getKeepAliveSeconds());
        //线程名字前缀
        executor.setThreadNamePrefix("default-thread-");
    /*
      当poolSize已达到maxPoolSize,如何处理新任务(是拒绝还是交由其它线程处理)
      CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
     */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 异步任务中异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error("==========================" + ex.getMessage() + "=======================", ex);
            log.error("exception method:" + method.getName());
        };
    }
}

二、使用

@Slf4j
@Service
@AllArgsConstructor
public class DemoExecuteTask {

	/**
	 * 线程池执行方法
	 */
	@Async("taskExecutor")
	public void testExecute() {
        //业务方法编写
	}

}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用多线程可以通过Java的Thread类或者使用Spring提供的线程池来实现。下面我会给你两个示例来说明。 使用Java的Thread类: ```java import org.springframework.stereotype.Component; @Component public class MyThread implements Runnable { @Override public void run() { // 在这里编写你的多线程代码逻辑 System.out.println("Hello from thread!"); } } ``` 然后,在你的业务逻辑中调用这个线程: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private MyThread myThread; @GetMapping("/startThread") public String startThread() { Thread thread = new Thread(myThread); thread.start(); return "Thread started"; } } ``` 当你访问`/startThread`时,将会启动一个新的线程并执行`MyThread`中的`run`方法。 使用Spring提供的线程池: 首先,在你的Spring Boot配置文件中配置线程池的相关属性: ``` spring.task.execution.pool.core-size=5 spring.task.execution.pool.max-size=10 spring.task.execution.pool.queue-capacity=1000 ``` 然后,创建一个异步方法: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class MyService { @Async public void processAsync() { // 在这里编写你的多线程代码逻辑 System.out.println("Hello from asynchronous method!"); } } ``` 最后,在你的业务逻辑中调用这个异步方法: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/startAsync") public String startAsync() { myService.processAsync(); return "Asynchronous method started"; } } ``` 当你访问`/startAsync`时,将会异步执行`MyService`中的`processAsync`方法。 这两种方式都可以在Spring Boot中实现多线程,具体选择哪种方式取决于你的需求和场景。希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值