package org.jeecg.async;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 使用 CompletableFuture 进行异步任务处理
 */
@Slf4j
@Service
@AllArgsConstructor
public class DirectCompletableFutureService {

    @Autowired
    @Qualifier("businessTaskExecutor")
    private ThreadPoolTaskExecutor businessTaskExecutor;


    /**
     * 执行有返回值的异步任务
     */
    public CompletableFuture<String> executeTaskWithResult(String taskData) {
        // 使用 supplyAsync 并指定自定义线程池
        return CompletableFuture.supplyAsync(() -> {
            // 这里是你的异步任务逻辑
            System.out.println("执行线程: " + Thread.currentThread().getName());
            return "处理结果: " + taskData;
        }, businessTaskExecutor); // 关键：传入线程池实例
    }

    /**
     * 执行无返回值的异步任务
     */
    public CompletableFuture<Void> executeTaskWithoutResult() {
        // 使用 runAsync 并指定自定义线程池
        return CompletableFuture.runAsync(() -> {
            // 异步任务逻辑
            System.out.println("执行线程: " + Thread.currentThread().getName());
            System.out.println("执行无返回值任务");
        }, businessTaskExecutor);
    }
}