java - 节点 response.end() 等效于 spring
问题描述
春天有什么方法可以立即发送响应。
我想创建一个可以完成工作的线程。但我不想让用户等到该工作完成。
解决方案
在 Spring 中有多种方法可以这样做。
这是他们的文章。
如果要异步进行操作,最简单的方法是使用@Asyn
Spring 中的注解。
这是一个简单的例子:
// 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 管理。
推荐阅读
- react-native - 在 this.props.navigation.navigate 中反应原生模板文字
- vba - 如何在 MS Access 中计算员工服务并保存在表字段中。(不是通过查询)
- typescript - 如何使用 NestJS graphql 上传多个文件?
- django - Django 使用页面 slud/id 上传图片
- ios - 控制器首次出现时获取可见项目?
- error-handling - 如何在 Stencil 应用程序中执行错误处理
- c# - NLog - 如果没有新消息,如何在每日更改时归档日志文件
- sql - 使用 Postgres 插入额外的行
- python - 如何从 json 中获取数字并相应地添加 Flask-WTForms 字段
- python - 适用于 Python 的 VSCode 运行按钮不显示正确的输出