节点 response.end() 等效于 spring

node response.end() equivalent in spring

在spring中有什么方法可以立即发送响应。

我想创建一个线程来完成一项工作。但我不想让用户等到该工作完成。

在 Spring 中有多种方法可以做到这一点。

这是他们的article

如果要异步操作,最简单的方法是使用 Spring 中的 @Asyn 注释。

这是一个简单的例子:

// Interface definition for your async operation here
public interface AsyncOperator {

    @Async
    void launchAsync(String aBody);
}

以及使用接口的简单实现

// Need to be a bean managed by Spring to be async
@Component
class SimpleAsync implements AsyncOperator {
    @Override
    public void launchAsync(String aBody){
        // Your async operations here
    }
}

然后您需要 Spring 配置异步的工作方式。使用 Spring 启动一个简单的配置 class 就像这样:

@Configuration
@EnableAsync
public class AsyncConfiguration {
}

然后您可以调用您的方法,它会立即 return 并异步进行处理:

@Component
public class AController {
    private final AsyncOperator async;
    public AController(AsyncOperator async){
        this.async = async;
    }

    public String aMethod(String body){
        // here it will return right after call
        this.async.launchAsync(body);

        return "Returned right away !!";
    }
}

此方法的唯一缺点是所有用于异步操作的 classes 必须由 Spring 管理。