本文最后更新于 2025-03-30,文章内容可能已经过时。



package cn.cloverdo.formesp.controller;

import cn.cloverdo.formesp.service.FoxService;
import cn.cloverdo.formesp.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.sql.SQLException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@CrossOrigin(origins = "*") // 允许所有来源
@RestController
public class FoxController {
    @Autowired
    private FoxService foxService;

    @Autowired
    private LogService logService;

    // 创建线程池用于异步处理
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @PostMapping("/fox")
    public String handleFoxRequest(@RequestBody String foxjson) {
        // 直接处理并返回结果,不等待其他操作
        return foxService.ApiFox(foxjson);
    }

    @PostMapping("/log")
    public DeferredResult<String> handleLogRequest(@RequestBody String foxjson) {
        // 创建延迟结果对象,设置超时为10秒
        DeferredResult<String> deferredResult = new DeferredResult<>(10000L);

        // 异步执行LogService的处理
        CompletableFuture.supplyAsync(() -> {
            try {
                // LogService在这里执行,包含3秒延迟
                return logService.LogCheck(foxjson);
            } catch (SQLException | InterruptedException e) {
                return "Error: " + e.getMessage();
            }
        }, executorService).thenAccept(deferredResult::setResult);

        // 立即返回DeferredResult,不阻塞当前线程
        return deferredResult;
    }
}

https://vip.123pan.cn/1813026721/yk6baz03t0l000d7w33fcfu3dkd5yegzDIYPDwavAqUvDGxPBIewAa==.png