import com.traffic.admin.common.configures.SystemConfig;
import lombok.RequiredArgsConstructor;
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.ThreadPoolExecutor;
@EnableAsync
@Configuration
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ThreadPoolConfig {
private final SystemConfig systemConfig;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
//创建线程池对象
ThreadPoolTaskExecutor asyncTaskThreadPool = new ThreadPoolTaskExecutor();
//线程池维护线程的最少数量
asyncTaskThreadPool.setCorePoolSize(systemConfig.getAsyncCorePoolSize());
//线程池维护线程的最大数量
asyncTaskThreadPool.setMaxPoolSize(systemConfig.getAsyncMaxPoolSize());
//线程池维护线程所允许的空闲时间
asyncTaskThreadPool.setKeepAliveSeconds(systemConfig.getAsyncKeepAliveSeconds());
//线程池所使用的缓冲队列
asyncTaskThreadPool.setQueueCapacity(systemConfig.getAsyncQueueCapacity());
//配置线程池中的线程的名称前缀
asyncTaskThreadPool.setThreadNamePrefix(systemConfig.getAsyncThreadNamePrefix());
// 等待所有任务结束后再关闭线程池
asyncTaskThreadPool.setWaitForTasksToCompleteOnShutdown(systemConfig.getAsyncWaitCompleteShutdown());
// 线程池对拒绝任务(无线程可用)的处理策略
asyncTaskThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//初始化
asyncTaskThreadPool.initialize();
return asyncTaskThreadPool;
}
}
#线程池维护线程的最少数量
system.async_core_pool_size=50
#线程池维护线程的最大数量
system.async_max_pool_size=200
#线程池维护线程所允许的空闲时间
system.async_keep_alive_seconds=300
#线程池所使用的缓冲队列
system.async_queue_capacity=1000
#配置线程池中的线程的名称前缀
system.async_thread_name_prefix=async-service-
#等待所有任务结束后再关闭线程池
system.async_wait_complete_shutdown=true
@Getter
@Setter
@Component
@SuppressWarnings("all")
@ConfigurationProperties(prefix = "system")
@PropertySource(value = {"classpath:/config/system-config-${spring.profiles.active}.properties",
"file:./config/config/system-config-${spring.profiles.active}.properties"}, ignoreResourceNotFound = true)
public class SystemConfig {
/**
* 线程池维护线程的最少数量
*/
private Integer asyncCorePoolSize;
/**
* 线程池维护线程的最大数量
*/
private Integer asyncMaxPoolSize;
/**
* 线程池维护线程所允许的空闲时间
*/
private Integer asyncKeepAliveSeconds;
/**
* 线程池所使用的缓冲队列
*/
private Integer asyncQueueCapacity;
/**
* 配置线程池中的线程的名称前缀
*/
private String asyncThreadNamePrefix;
/**
* 等待所有任务结束后再关闭线程池
*/
private Boolean asyncWaitCompleteShutdown;
}
使用
import com.traffic.admin.common.response.Response;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@Api(tags = "测试")
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TestController {
private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
private final RunAsyncTest runAsyncTest;
@GetMapping("/runAsync")
public Response<String> CompletableFuture(){
CompletableFuture.runAsync(runAsyncTest,threadPoolTaskExecutor);
return Response.ok("ok");
}
}
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
@Component
public class RunAsyncTest implements Runnable{
@SneakyThrows
@Override
public void run() {
Thread.sleep(50000);
System.out.println("async run...................");
}
}
public List<OperationInformationVo> getOperationInformation(BasicQuery basicQuery) {
//查询条件
Map<String, Object> queryMap = BuilderUtils.of(HashMap<String, Object>::new)
.with(StringUtils.isNotBlank(TimeInterval.getFormat(basicQuery.getTimeInterval())), Map::put, "format", TimeInterval.getFormat(basicQuery.getTimeInterval()))
.with(Objects.nonNull(basicQuery.getStartTime()), Map::put, "stageIaStartTime", LocalDateTimeUtils.ofDate(basicQuery.getStageIaStartTime()))
.with(Objects.nonNull(basicQuery.getStartTime()), Map::put, "startTime", LocalDateTimeUtils.ofDate(basicQuery.getStartTime()))
.with(Objects.nonNull(basicQuery.getEndTime()), Map::put, "stageIaEndTime", LocalDateTimeUtils.ofDate(basicQuery.getStageIaEndTime()))
.with(Objects.nonNull(basicQuery.getEndTime()), Map::put, "endTime", LocalDateTimeUtils.ofDate(basicQuery.getEndTime()))
.build();
//异步任务集合
List<CompletableFuture<OperationInformationVo>> futures = BuilderUtils.of(ArrayList<CompletableFuture<OperationInformationVo>>::new)
.with(List::add, CompletableFuture.supplyAsync(() -> Optional.ofNullable(taxiRevenusStatisticsMapper.selectOperationOrderCount(queryMap))
.map(orderDto -> BuilderUtils.of(OperationInformationVo::new)
.with(OperationInformationVo::setType, OperationVehicleType.TAXI.getInfo())
.with(OperationInformationVo::setCurrentOrdersCount, orderDto.getCurrentOrdersCount())
.with(OperationInformationVo::setStageIaOrdersCount, orderDto.getStageIaOrdersCount())
.build())
.orElse(new OperationInformationVo()), threadPoolTaskExecutor))
.with(List::add, CompletableFuture.supplyAsync(() -> Optional.ofNullable(taskBikeBasicMapper.selectOperationOrderCount(queryMap))
.map(orderDto -> BuilderUtils.of(OperationInformationVo::new)
.with(OperationInformationVo::setType, OperationVehicleType.BICYCLE.getInfo())
.with(OperationInformationVo::setCurrentOrdersCount, orderDto.getCurrentOrdersCount())
.with(OperationInformationVo::setStageIaOrdersCount, orderDto.getStageIaOrdersCount())
.build())
.orElse(new OperationInformationVo()), threadPoolTaskExecutor))
.with(List::add, CompletableFuture.supplyAsync(() -> Optional.ofNullable(transportRepStatisticsMapper.selectOperationOrderCount(queryMap))
.map(orderDto -> BuilderUtils.of(OperationInformationVo::new)
.with(OperationInformationVo::setType, OperationVehicleType.RAIL_TRANSIT.getInfo())
.with(OperationInformationVo::setCurrentOrdersCount, orderDto.getCurrentOrdersCount())
.with(OperationInformationVo::setStageIaOrdersCount, orderDto.getStageIaOrdersCount())
.build())
.orElse(new OperationInformationVo()), threadPoolTaskExecutor))
.with(List::add, CompletableFuture.supplyAsync(() -> Optional.ofNullable(baseStatisticsMapper.selectOperationOrderCount(queryMap))
.map(orderDto -> BuilderUtils.of(OperationInformationVo::new)
.with(OperationInformationVo::setType, OperationVehicleType.CITY_BUS.getInfo())
.with(OperationInformationVo::setCurrentOrdersCount, orderDto.getCurrentOrdersCount())
.with(OperationInformationVo::setStageIaOrdersCount, orderDto.getStageIaOrdersCount())
.build())
.orElse(new OperationInformationVo()), threadPoolTaskExecutor))
.build();
// 获得所有子任务的处理结果,使用allOf方法来表示所有的并行任务
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply(v ->
futures.stream().map(CompletableFuture::join).collect(Collectors.toList())).join();
}
@Api(tags = "测试")
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TestController {
private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
private final RunAsyncTest runAsyncTest;
private final TestService testService;
private final TestService2 testService2;
@GetMapping("/runAsync")
public Response<String> CompletableFuture(){
List<CompletableFuture> futures =new ArrayList<>();
CompletableFuture.runAsync(runAsyncTest,threadPoolTaskExecutor);
futures.add(CompletableFuture.supplyAsync(()->testService.getVo(),threadPoolTaskExecutor));
futures.add(CompletableFuture.supplyAsync(()->testService2.getVo(),threadPoolTaskExecutor));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply(v->
futures.stream().map(CompletableFuture::join).collect(Collectors.toList())).join();
return Response.ok("ok");
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* 通用的 Builder 模式构建器
*
*/
public class BuilderUtils<T> {
private final Supplier<T> instantiator;
private final List<Consumer<T>> modifiers = new ArrayList<>();
public BuilderUtils(Supplier<T> instantiator) {
this.instantiator = instantiator;
}
public static <T> BuilderUtils<T> of(Supplier<T> instantiate) {
return new BuilderUtils<>(instantiate);
}
public <P1> BuilderUtils<T> with(Consumer1<T, P1> consumer, P1 p1) {
Consumer<T> c = instance -> consumer.accept(instance, p1);
modifiers.add(c);
return this;
}
public <P1> BuilderUtils<T> with(boolean condition, Consumer1<T, P1> consumer, P1 p1) {
if(condition) {
Consumer<T> c = instance -> consumer.accept(instance, p1);
modifiers.add(c);
}
return this;
}
public <P1, P2> BuilderUtils<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
modifiers.add(c);
return this;
}
public <P1, P2> BuilderUtils<T> with(boolean condition, Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
if(condition) {
Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
modifiers.add(c);
}
return this;
}
public <P1, P2, P3> BuilderUtils<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
modifiers.add(c);
return this;
}
public <P1, P2, P3> BuilderUtils<T> with(boolean condition, Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
if(condition) {
Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
modifiers.add(c);
}
return this;
}
public T build() {
T value = instantiator.get();
modifiers.forEach(modifier -> modifier.accept(value));
modifiers.clear();
return value;
}
/**
* 1 参数 Consumer
*/
@FunctionalInterface
public interface Consumer1<T, P1> {
void accept(T t, P1 p1);
}
/**
* 2 参数 Consumer
*/
@FunctionalInterface
public interface Consumer2<T, P1, P2> {
void accept(T t, P1 p1, P2 p2);
}
/**
* 3 参数 Consumer
*/
@FunctionalInterface
public interface Consumer3<T, P1, P2, P3> {
void accept(T t, P1 p1, P2 p2, P3 p3);
}
}