【问题标题】:node response.end() equivalent in spring节点 response.end() 等效于 spring
【发布时间】:2020-01-17 00:51:56
【问题描述】:

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

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

【问题讨论】:

    标签: java node.js spring http servlets


    【解决方案1】:

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

    @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 管理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2020-05-10
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多