ThreadPoolConfigProperties.java
package com.kaki.gulimall.product.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "gulimall.thread")//这个注解的意思是绑定配置文件
@Component//这个配置也需要加入到容器中才能生效
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
pom.xml
<!--在 ThreadPoolConfigProperties 加上注解@ConfigurationProperties 弹出一个红提示框 说可以加上这个
spirng 的元数据处理器 这样以后就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
application.properties
gulimall.thread.core-size=20
gulimall.thread.keep-alive-time=10
gulimall.thread.max-size=200
然后就可以在MyThreadConfig.java中使用
//@EnableConfigurationProperties(ThreadPoolConfigProperties.class)//可以指定要开启哪个配置 如果没在@ConfigurationProperties那个类里
//加 @Component注解 就必须在这里指定 如果那边已经加了Component 已经注入到容器了 这里就可以不写
//直接在 @Bean的方法中使用
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool){//使用与配置文件绑定的类作为参数
return new ThreadPoolExecutor(pool.getCoreSize(),
pool.getMaxSize(),
pool.getKeepAliveTime(),
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000)
, Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
}