springboot如何自定义线程池

  我这里采用的是多环境配置

(1)编写配置文件application.properties

server.port=8080
server.servlet.context-path=/demo1
#指定多环境配置文件
spring.profiles.active=dev

(2)编写配置文件application-dev.properties

#日志
logging.config=classpath:logback-spring.xml
logging.file.path=D:/log/nms
logging.level.com.baidu.dao=debug
logging.level.com.baidu=info
#自定义线程
#核心线程数
task.pool.corePoolSize=20
#最大线程数
task.pool.maxPoolSize=40
#线程存活时间
task.pool.keepAliveSeconds=300
#队列
task.pool.queueCapacity=50

(3)系统生成的日志文件(logback-spring.xml)

<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <springProperty scope="context" name="logPath" source="log.path" defaultValue="localhost"/>
    <contextName>logback</contextName>
    <logger name="org.quartz" level="ERROR"/>
    <!--输出到控制台-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
             <level>ERROR</level>
         </filter>-->
        <encoder>
            <pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--按天生成日志-->
    <appender name="logFile"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <Prudent>true</Prudent>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>
                ${logPath}/%d{yyyy-MM-dd}.log
            </FileNamePattern>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} -%msg%n
            </Pattern>
        </layout>
    </appender>

    <root level="error">
        <appender-ref ref="console" />
        <appender-ref ref="logFile" />
    </root>
    <logger level="ERROR" name="org.springframework.boot.autoconfigure.logging"  additivity="false">
        <appender-ref ref="console"/>
        <appender-ref ref="logFile" />
    </logger>

    <!-- <logger name="com.pos" level="INFO" additivity="false">
        <appender-ref ref="console"/>
    </logger> -->
</configuration>

 (4)创建config包在其下面编写AsyncTaskConfig.java

package com.baidu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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;

/**
 * Description: AsyncTaskConfig
 * Author: QinWeiTao
 * Create Date: 20/6/29
 */

@EnableAsync
@Configuration
@EnableConfigurationProperties({AsyncTaskProperties.class} )
public class AsyncTaskConfig {
	@Autowired
	AsyncTaskProperties properties;

	@Bean
	public Executor asyncTaskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(properties.getCorePoolSize());
		executor.setMaxPoolSize(properties.getMaxPoolSize());
		executor.setQueueCapacity(properties.getQueueCapacity());
		executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
		//配置线程池中的线程的名称前缀
		executor.setThreadNamePrefix("task-");
		// rejection-policy:当pool已经达到max size的时候,丢弃任务
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
		//执行初始化
		executor.initialize();
		return executor;
	}
}

 AsycTask.java这里一般放的是要多线程的代码一般直接调用就可以了

package com.baidu.config;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AsyncTask {
    @Async("asyncTaskExecutor")  //myTaskAsynPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池
    public void doTask1(int i) throws InterruptedException{
        //获取方法的全限定名
        final String name = AsyncTask.class.getName();
        //截取方法名
        final String substring = name.substring(17, name.length());
        /**
         *
         * 使用split方法也可以截取名称
         final String name = AsyncTask.class.getName();
         final String[] split = name.split("\\.");
         final String s = split[3].toString();
         * */
        System.out.println("调用多线程实现结果"+"方法名称"+substring+"调用的值"+i);
    }
}

创建对应的线程池的实体类 

package com.baidu.config;

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

/**
 * Description: AsyncTaskProperties
 * Author: QinWeiTao
 * Create Date: 20/6/29
 */

@Data
@ConfigurationProperties(prefix = "task.pool")
public class AsyncTaskProperties {
	private int corePoolSize;
	private int maxPoolSize;
	private int keepAliveSeconds;
	private int queueCapacity;
}

测试接口效果

package com.baidu.demo1;

import com.baidu.config.AsyncTask;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

@SpringBootTest
public class Demo1ApplicationTests {
@Autowired
AsyncTask asyncTask;
    @Test
    public   void contextLoads() throws InterruptedException {
        final String name = Thread.currentThread().getName();
        System.out.println("主线程的名称"+name);
        //调用多线程方法
        asyncTask.doTask1(1);
    }
}

测试结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

把柄

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

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

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

打赏作者

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

抵扣说明:

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

余额充值