package com.greenorange.promotion.timeout;

import org.junit.jupiter.api.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("/executeAsync")
    public String executeAsync() {
        CompletableFuture<String> future = myService.longRunningTask();

        try {
            // 设置超时时间为5秒，如果5秒后任务仍未完成则抛出 TimeoutException
            return future.get(2000, TimeUnit.MILLISECONDS); // 设置5秒超时
        } catch (TimeoutException e) {
            return "Request timed out";
        } catch (Exception e) {
            return "An error occurred: " + e.getMessage();
        }
    }
}
