SpringBoot-ThreadPoolExecutor实例demo

本章节为基于SpringBoot 通过注解方式实现ThreadPoolExecutor实例,步骤过程如下:

 

1、定义ExecutorConfig类,用于配置、初始化ThreadPoolTaskExecutor类

package com.example.threadpooldemo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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);

    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    @Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2、定义ThreadPoolTaskExecutor类属性配置源文件-application.properties

# 异步线程配置
# 配置核心线程数
async.executor.thread.core_pool_size = 5
# 配置最大线程数
async.executor.thread.max_pool_size = 5
# 配置队列大小
async.executor.thread.queue_capacity = 99999
# 配置线程池中的线程的名称前缀
async.executor.thread.name.prefix = async-service-

3、定义异步服务接口和实现类

package com.example.threadpooldemo.config;

public interface AsyncService {
    /**
     * 执行异步任务
     * 可以根据需求,自己加参数拟定,我这里就做个测试演示
     */
    void executeAsync();
}


package com.example.threadpooldemo.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements  AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync() {
        logger.info("start executeAsync");
        System.out.println("异步线程要做的事情");
        System.out.println("可以在这里执行批量插入等耗时的事情");
        logger.info("end executeAsync");
    }
}
实现类AsyncServiceImpl 中public void executeAsync() 通过@Async("asyncServiceExecutor")注解 关联ExecutorConfig类 @Bean(name = "asyncServiceExecutor") ,即executeAsync方法进入的线程池是asyncServiceExecutor方法来创建

4、Controller:通过注解@Autowired注入并调用Service

package com.example.threadpooldemo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/*Spring Restful风格*/
@RestController
public class AyncControlller {

    @Autowired
    private AsyncService asyncService;

    /*外部资源映射-http://localhost:8080/async*/
    @GetMapping("/async")
    public void async(){
        asyncService.executeAsync();
    }
}

5、测试-postmain [http://localhost:8080/async]

2021-05-17 17:13:59.331  INFO 17516 --- [async-service-1] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:13:59.332  INFO 17516 --- [async-service-1] c.e.t.config.AsyncServiceImpl            : end executeAsync
2021-05-17 17:14:00.047  INFO 17516 --- [async-service-2] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:14:00.047  INFO 17516 --- [async-service-2] c.e.t.config.AsyncServiceImpl            : end executeAsync
2021-05-17 17:14:00.754  INFO 17516 --- [async-service-3] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:14:00.754  INFO 17516 --- [async-service-3] c.e.t.config.AsyncServiceImpl            : end executeAsync
2021-05-17 17:14:01.429  INFO 17516 --- [async-service-4] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:14:01.429  INFO 17516 --- [async-service-4] c.e.t.config.AsyncServiceImpl            : end executeAsync
2021-05-17 17:14:02.052  INFO 17516 --- [async-service-5] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:14:02.052  INFO 17516 --- [async-service-5] c.e.t.config.AsyncServiceImpl            : end executeAsync
2021-05-17 17:14:02.687  INFO 17516 --- [async-service-1] c.e.t.config.AsyncServiceImpl            : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2021-05-17 17:14:02.687  INFO 17516 --- [async-service-1] c.e.t.config.AsyncServiceImpl            : end executeAsync

  默认线程数为5.

PS:pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>threadpooldemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>threadpooldemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

### Spring BootThreadPoolExecutor 的实现与配置 在 Spring Boot 应用中,`ThreadPoolExecutor` 是一种常用的线程池管理工具,用于高效地管理和调度任务。通过合理配置 `ThreadPoolExecutor`,可以显著提升应用性能并优化资源利用。 #### 配置自定义线程池 Bean 为了在 Spring Boot 中使用 `ThreadPoolExecutor`,可以通过创建一个自定义的线程池 Bean 来实现。以下是具体方法: 1. **引入依赖** 如果尚未引入必要的依赖库,则需确保项目的 `pom.xml` 文件中有以下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 2. **定义线程池 Bean** 创建一个配置类来声明线程池 Bean,并设置其核心参数。这些参数包括但不限于核心线程数、最大线程数、队列容量以及拒绝策略等[^3]。 下面是一个典型的线程池配置示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; @Configuration public class ThreadPoolConfig { @Bean(name = "customTaskExecutor") public ThreadPoolExecutor taskExecutor() { int corePoolSize = 5; // 核心线程数量 int maxPoolSize = 10; // 最大线程数量 long keepAliveTime = 60L; // 线程存活时间(秒) int queueCapacity = 100; // 队列容量 RejectedExecutionHandler handler = new AbortPolicy(); // 设置拒绝策略 return new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, java.util.concurrent.TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), new ThreadPoolExecutor.CallerRunsPolicy() ); } } ``` 3. **注入并使用线程池** 定义完成后,在服务层或其他组件中可通过自动装配的方式获取该线程池实例,并提交异步任务给它处理。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.concurrent.Future; @Service public class TaskService { private final ThreadPoolExecutor executor; @Autowired public TaskService(ThreadPoolExecutor executor) { this.executor = executor; } public void executeTask(Runnable task) { executor.execute(task); } public Future<?> submitTask(Callable<?> callable) { return executor.submit(callable); } } ``` 4. **调整拒绝策略** 当线程池中的任务过多而无法及时处理时,可以选择不同的拒绝策略以应对这种情况。常见的拒绝策略有四种:AbortPolicy、CallerRunsPolicy、DiscardOldestPolicy 和 DiscardPolicy。可以根据实际需求灵活选用合适的策略。 #### 性能调优建议 - 合理设定线程池的核心大小和最大大小,避免因线程过载而导致系统崩溃。 - 对于高并发场景下可能存在的大量短生命周期任务,应适当增加队列长度或采用更高效的阻塞队列结构。 - 使用监控工具跟踪线程池运行状态,以便动态调整相关参数。 ```java // 示例代码片段展示如何捕获异常情况下的日志记录逻辑 try { future.get(); } catch (Exception e) { log.error("Error occurred while processing the task", e); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值