首页 > 解决方案 > 节点 response.end() 等效于 spring

问题描述

春天有什么方法可以立即发送响应。

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

标签: javanode.jsspringhttpservlets

解决方案


在 Spring 中有多种方法可以这样做。

这是他们的文章

如果要异步进行操作,最简单的方法是使用@AsynSpring 中的注解。

这是一个简单的例子:

// 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 启动一个简单的配置类,如下所示:

@Configuration
@EnableAsync
public class AsyncConfiguration {
}

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

@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 !!";
    }
}

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


推荐阅读