springboot整合线程池最佳实践,赶紧学起来!

封装ThreadPoolTaskExecutor线程池

1、新增application.yml配置

这里主要是配置ThreadPoolTastExecutor比较重要的参数

thread:
  poolexecutor:
    corePoolSize: 10 # 核心线程数量
    maxPoolSize: 30 # 最大线程数量
    queueCapacity: 100 # 队列长度
    keppAliveSeconds: 60 # 存活时间
    prefixName: "taskExecutor-" # 线程名称前缀

2、properties类

这个是为了简化代码,不用@Value一个一个去获取值

package com.walker.async.common.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Data
@ConfigurationProperties(prefix = "thread.poolexecutor")
public class ThreadPoolProperties {
    private Integer corePoolSize;
    private Integer maxPoolSize;
    private Integer queueCapacity;
    private Integer keppAliveSeconds;
    private String prefixName;
}


3、配置类

配置线程池,并将其注入到bean中

package com.walker.async.common.config;

import com.walker.async.common.properties.ThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
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;

//开启异步
@EnableAsync
//配置类
@Configuration
public class ThreadPoolConfig {
    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    //bean名称
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeppAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getPrefixName());
        //设置线程池关闭的时候 等待所有的任务完成后再继续销毁其他的bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

4、封装Service和service实现类,方便管理

package com.walker.async.service.async;

public interface TestAsync {

    void doAsync();
}

package com.walker.async.service.async.impl;

import com.walker.async.service.async.TestAsync;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class TestAsyncImpl implements TestAsync {


    @Override
    //使用@Async,并将前面的注册的bean,填写到Async的value中
    @Async("taskExecutor")
    public void doAsync() {
        log.info("== async start==");
        log.info("线程{}执行代码逻辑",Thread.currentThread().getName());
        log.info("== async end==");
    }
}

5、测试

package com.walker.async;

import com.walker.async.service.async.TestAsync;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class AsyncTest {
    //引用类
    @Autowired
    private TestAsync testAsync;

    @Test
    void test(){
        for (int i = 0; i < 10; i++) {
            testAsync.doAsync();
        }

    }
}

返回结果:

2023-01-29 16:47:12.491  INFO 13332 --- [ taskExecutor-2] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.491  INFO 13332 --- [ taskExecutor-1] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.493  INFO 13332 --- [ taskExecutor-4] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.493  INFO 13332 --- [ taskExecutor-3] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.493  INFO 13332 --- [ taskExecutor-5] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.501  INFO 13332 --- [ taskExecutor-9] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.501  INFO 13332 --- [taskExecutor-10] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.500  INFO 13332 --- [ taskExecutor-7] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.502  INFO 13332 --- [ taskExecutor-8] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.500  INFO 13332 --- [ taskExecutor-6] c.w.a.service.async.impl.TestAsyncImpl   : == async start==
2023-01-29 16:47:12.502  INFO 13332 --- [ taskExecutor-6] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-6执行代码逻辑
2023-01-29 16:47:12.501  INFO 13332 --- [ taskExecutor-5] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-5执行代码逻辑
2023-01-29 16:47:12.503  INFO 13332 --- [ taskExecutor-5] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.492  INFO 13332 --- [ taskExecutor-2] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-2执行代码逻辑
2023-01-29 16:47:12.503  INFO 13332 --- [ taskExecutor-2] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.503  INFO 13332 --- [ taskExecutor-6] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.501  INFO 13332 --- [ taskExecutor-9] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-9执行代码逻辑
2023-01-29 16:47:12.492  INFO 13332 --- [ taskExecutor-1] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-1执行代码逻辑
2023-01-29 16:47:12.506  INFO 13332 --- [ taskExecutor-1] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.506  INFO 13332 --- [ taskExecutor-9] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.493  INFO 13332 --- [ taskExecutor-3] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-3执行代码逻辑
2023-01-29 16:47:12.501  INFO 13332 --- [taskExecutor-10] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-10执行代码逻辑
2023-01-29 16:47:12.506  INFO 13332 --- [ taskExecutor-3] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.506  INFO 13332 --- [taskExecutor-10] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.502  INFO 13332 --- [ taskExecutor-8] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-8执行代码逻辑
2023-01-29 16:47:12.506  INFO 13332 --- [ taskExecutor-8] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.502  INFO 13332 --- [ taskExecutor-7] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-7执行代码逻辑
2023-01-29 16:47:12.508  INFO 13332 --- [ taskExecutor-7] c.w.a.service.async.impl.TestAsyncImpl   : == async end==
2023-01-29 16:47:12.493  INFO 13332 --- [ taskExecutor-4] c.w.a.service.async.impl.TestAsyncImpl   : 线程taskExecutor-4执行代码逻辑
2023-01-29 16:47:12.508  INFO 13332 --- [ taskExecutor-4] c.w.a.service.async.impl.TestAsyncImpl   : == async end==

可以发现,该方法使用了线程池.

6、打印线程池情况(自主选择)

  • 编写ThreadPoolTaskExecutor继承类
package com.walker.async.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
//1、继承ThreadPoolTaskExecutor
public class VisibleThreadPoolTaskExecutor extends ThreadPoolTaskExecutor  {

    
    //2、编写打印线程池方法
    private void log(String method){
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

        if(threadPoolExecutor==null){
            return;
        }

        log.info("线程池:{}, 执行方法:{},任务数量 [{}], 完成任务数量 [{}], 活跃线程数 [{}], 队列长度 [{}]",
                this.getThreadNamePrefix(),
                method,
                threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }


    
    //3、重写方法,进行日志的记录
    @Override
    public void execute(Runnable task) {
        log("execute");
        super.execute(task);
    }

    @Override
    public void execute(Runnable task, long startTimeout) {
        log("execute");
        super.execute(task, startTimeout);
    }

    @Override
    public Future<?> submit(Runnable task) {
        log("submit");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        log("submit");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        log("submitListenable");
        return super.submitListenable(task);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        log("submitListenable");
        return super.submitListenable(task);
    }
}

  • 重新编写线程池配置类
package com.walker.async.common.config;

import com.walker.async.common.properties.ThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
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;

@EnableAsync
@Configuration
public class ThreadPoolConfig {
    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeppAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getPrefixName());
        //设置线程池关闭的时候 等待所有的任务完成后再继续销毁其他的bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }


    
    @Bean("visibleTaskExecutor")
    public Executor visible() {

        //1、使用VisibleThreadPoolTaskExecutor作为类
        ThreadPoolTaskExecutor executor = new VisibleThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeppAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getPrefixName());
        //设置线程池关闭的时候 等待所有的任务完成后再继续销毁其他的bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

  • service和实现类也重新编写
void visibleAsync();

    /**
    * 可视化,可以打印线程池情况
    */
    @Override
    @Async("visibleTaskExecutor")
    public void visibleAsync() {
        log.info("== async start==");
        log.info("线程{}执行代码逻辑",Thread.currentThread().getName());
        log.info("== async end==");
    }
  • 测试
package com.walker.async;

import com.walker.async.service.async.TestAsync;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class AsyncTest {
    @Autowired
    private TestAsync testAsync;


    @Test
    void test(){
        for (int i = 0; i < 10; i++) {
//            testAsync.doAsync();
            testAsync.visibleAsync();
        }
    }
}

  • 返回结果

image.png
每次执行的时候,都会打印对应的线程池情况了

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot中,可以通过整合线程池来实现对多线程任务的管理和调度。当我们启动Spring Boot项目时,可以在Spring容器中注入一个线程池,并通过@Resource或@Autowired注解将其注入到需要使用线程池的类中。 线程池的原理类似于数据库连接池,它将多个线程对象放入一个池子中,可以从池子中获取、使用和回收线程。每个线程在一段时间内只能执行一个任务,而线程池中的各个线程是可以重复使用的。这样可以提高线程的复用性和效率。 在Spring Boot整合线程池的步骤如下: 1. 创建线程池配置类,使用@ConfigurationProperties注解将配置文件中以"thread.pool"开头的配置信息绑定到对应的字段上。例如,配置文件中的"thread.pool.core-pool-size"对应字段就是corePoolSize。同时,使用@Component注解将该类交由Spring容器管理。 2. 在配置类中定义线程池的相关属性,包括核心线程数、最大线程数、空闲时间、等待队列长度等。 3. 在需要使用线程池的类中,通过@Resource或@Autowired注解将线程池注入进来即可使用。 通过以上步骤,就可以在Spring Boot项目中成功整合线程池,并且方便地使用线程池来处理多线程任务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [spring boot整合线程池](https://blog.csdn.net/doubiy/article/details/124219390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [线程池详解+springboot整合线程池(超级详细简洁代码可直接执行)](https://blog.csdn.net/qq_40595922/article/details/120856971)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

WalkerShen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值