springboot整合多线程

springboot整合多线程

本文参考网址:

https://mp.weixin.qq.com/s/vDqqE2PiNIsojgrQRb0QWA

SpringBoot使用@Async

https://mp.weixin.qq.com/s/xwTMXuHEpgFipiHrOuYgNA

ruoyi开源项目使用多线程配置

ruoyi开源项目地址

https://gitee.com/y_project/RuoYi-Vue

具体多项成配置

https://gitee.com/y_project/RuoYi-Vue/blob/master/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ThreadPoolConfig.java

ruoyi项目重 , 线程池具体配置

package com.ruoyi.framework.config;

import com.ruoyi.common.utils.Threads;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author ruoyi
 **/
@Configuration
public class ThreadPoolConfig
{
    // 核心线程池大小
    private int corePoolSize = 50;

    // 最大可创建的线程数
    private int maxPoolSize = 200;

    // 队列最大长度
    private int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService()
    {
        return new ScheduledThreadPoolExecutor(corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy())
        {
            @Override
            protected void afterExecute(Runnable r, Throwable t)
            {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }
        };
    }
}

封装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-20230313214251731

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值