线程池配置与CompletableFuture使用示例

线程池配置类
@Data
@Configuration
public class ThreadPoolConfig {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT;
    private static final int MAX_POOL_SIZE = CPU_COUNT * 2;

    @Bean("asyncTaskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        threadPoolTaskExecutor.setQueueCapacity(1200);
        threadPoolTaskExecutor.setThreadNamePrefix("asyncTaskExecutor-");
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
    
    @Bean("asyncSimpleExecutor")
    public SimpleAsyncTaskExecutor getAsyncSimpleExecutor() {
        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("asyncSimpleExecutor-");
        taskExecutor.setConcurrencyLimit(CORE_POOL_SIZE);
        return taskExecutor;
    }
}
CompletableFuture使用示例
@Service
public class DictService {
    @Autowired
    @Qualifier("asyncTaskExecutor")
    private Executor executor;

    public List<Dict> getDictList(Long parentId) throws ExecutionException, InterruptedException {
        CompletableFuture<List<Dict>> future = CompletableFuture.supplyAsync(
            () -> this.list(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, parentId)),
            executor
        );
        return future.get();
    }
}
异步任务处理优化
public CompletableFuture<List<Dict>> getDictListAsync(Long parentId) {
    return CompletableFuture.supplyAsync(
        () -> this.list(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, parentId)),
        executor
    );
}
异常处理方式
public List<Dict> getDictListWithExceptionHandling(Long parentId) {
    try {
        return CompletableFuture.supplyAsync(
            () -> this.list(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, parentId)),
            executor
        ).exceptionally(ex -> {
            log.error("查询字典列表失败", ex);
            return Collections.emptyList();
        }).get();
    } catch (InterruptedException | ExecutionException e) {
        Thread.currentThread().interrupt();
        return Collections.emptyList();
    }
}
多任务组合示例
public CompletableFuture<Map<String, Object>> getCombinedData(Long id) {
    CompletableFuture<List<Dict>> dictFuture = CompletableFuture.supplyAsync(
        () -> this.list(new LambdaQueryWrapper<Dict>()),
        executor
    );
    
    CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(
        () -> userService.getById(id),
        executor
    );
    
    return dictFuture.thenCombine(userFuture, (dicts, user) -> {
        Map<String, Object> result = new HashMap<>();
        result.put("dicts", dicts);
        result.put("user", user);
        return result;
    });
}
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐