定义一个异步线程池配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步线程池配置
**/
@Configuration
public class PoolConfiguration {
/**
* SpringBoot内置的多线程支持对应的线程池配置
* @return 一个线程池对象
*/
@Bean
public ThreadPoolTaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//默认线程名称
executor.setThreadNamePrefix("server-content-operate-");
//核心线程数
executor.setCorePoolSize(6);
//最大线程数
executor.setMaxPoolSize(20);
//队列容量
executor.setQueueCapacity(200);
//线程活跃时间
executor.setKeepAliveSeconds(60);
//拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.afterPropertiesSet();
return executor;
}
}
使用CompletableFuture
List<CompletableFuture<Void>> completableFutures = new ArrayList<>(16);
while (startOffset < endOffset){
log.info("=============================当前推送的开始偏移量是{}==========================", startOffset);
List<Long> seqList = historyNewsService.getSeqList(startOffset, size);
/
List<NewsHistoryPostDTO> newsHistoryPostDTOList = new ArrayList<>();
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
newsDetailService.completeHistoryNews(newsHistoryPostDTOList, seqList);
for(NewsHistoryPostDTO newsHistoryPostDTO : newsHistoryPostDTOList){
selectDeleteSystemService.sendHistoryNews(newsHistoryPostDTO);
}
return null;
},taskExecutor);
completableFutures.add(future);
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
.thenApply(justVoid-> completableFutures.stream()
.map(CompletableFuture::join).collect(Collectors.toList()));
startOffset = seqList.get(seqList.size() - 1);
redisTemplate.opsForValue().set(REDIS_KEY_OF_HISTORY_POST_OFFSET, String.valueOf(startOffset));
}