java - spring boot webflux:避免处理程序中的线程阻塞方法调用
问题描述
我才刚刚开始使用WebFlux
整个反应式范式,我被困在这个问题上:
@Component
public class AbcHandler {
private ObjectMapper objectMapper = new ObjectMapper();
public Mono<ServerResponse> returnValue() throws IOException {
Abc abc = objectMapper.readValue(new ClassPathResource("data/abc.json").getURL(), Abc.class);
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(abc));
}
}
IntelliJ 给了我警告,readValue()
并且toURL()
是线程阻塞方法调用。
我可以忽略这一点,或者我应该如何返回从文件系统读取并映射到域类的 JSON 结构?
我觉得这应该以某种异步方式或至少更“被动”地完成。
解决方案
您应该将它包装在 fromCallable 中,并确保它在自己的线程上运行。
@Autowire
private ObjectMapper objectMapper;
public Mono<ServerResponse> fooBar() throws IOException {
return Mono.fromCallable(() -> objectMapper.readValue(new ClassPathResource("data/Foo.json")
.getURL(), Foo.class))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(foo -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.bodyValue(foo));
}
推荐阅读
- postgresql - 如何使用 JDBC 从 postgres 读取 2300 万条记录?我必须从 postgres 中的表中读取并写入另一个表
- javascript - 如何检查数组中是否存在没有名称的对象?
- c# - [dotNET Core]将模型传递给视图 -> 将复选框与 POST 方法形式的数据绑定 -> 将整个模型发送到控制器
- css - CSS 重新创建基于荧光粉的终端屏幕的效果
- php - Php Sql 使用关键字搜索多个表并显示搜索结果
- excel - Excel 公式,用于查找 16 日是否在周六或周日,如果是,则返回下周一的日期
- c++ - C++ 不需要的舍入
- php - Opencart 3.0 循环获取类别 ID 的产品
- r - 用 Magick 制作的 R Gif 动态注释文本
- java - 调用 driver.quit() 和 driver.close() 时 Singleton 类如何控制?