top.doudou.common.tool.config.InitializationBean Maven / Gradle / Ivy
package top.doudou.common.tool.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import top.doudou.common.tool.config.entity.ExecutorProperties;
import top.doudou.common.tool.constant.PropertiesConstant;
import top.doudou.common.tool.context.SpringContextUtil;
import java.net.InetAddress;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Description
* @Author 傻男人 <[email protected]>
* @Date 2020-10-23 11:20
* @Version V1.0
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(ExecutorProperties.class)
public class InitializationBean {
@Autowired
private ApplicationContext context;
@Autowired
private ExecutorProperties executorProperties;
/**
* 启动成功打印本机地址与swagger地址
*/
@Bean
public ApplicationRunner applicationRunner() {
SpringContextUtil.setContext(context);
return applicationArguments -> {
Integer port = SpringContextUtil.getProperty(PropertiesConstant.PORT,Integer.class);
String contextPath = SpringContextUtil.getProperty(PropertiesConstant.CONTEXT_PATH);
if(null == port){
port = 8080;
}
if(StringUtils.isBlank(contextPath)){
contextPath = "";
}
log.info("启动成功:" + "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + contextPath);
Boolean swagger = SpringContextUtil.getProperty(PropertiesConstant.CUSTOM_SWAGGER,Boolean.class);
if(null != swagger && swagger){
log.info("swagger访问地址:" + "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port+contextPath+"/doc.html");
}
};
}
@Bean("executorService")
public TaskExecutor executorService(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(executorProperties.getCorePoolSize());
executor.setMaxPoolSize(executorProperties.getMaxPoolSize());
executor.setQueueCapacity(executorProperties.getCapacity());
executor.setKeepAliveSeconds(executorProperties.getKeepAliveSecond());
if(StringUtils.isBlank(executorProperties.getName())){
String applicationName = context.getEnvironment().getProperty(PropertiesConstant.APPLICATION_NAME);
if(StringUtils.isBlank(applicationName)){
applicationName = "default";
}
executorProperties.setName("async"+applicationName+"-pool-");
}
executor.setThreadNamePrefix(executorProperties.getName());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}