【问题标题】:How to convert a JdbcTemplate to Flux in Spring?如何在 Spring 中将 JdbcTemplate 转换为 Flux?
【发布时间】:2019-07-25 09:11:47
【问题描述】:

我有一个返回List<Item> 的现有服务。这些项目是由多个后续数据库调用、解析和聚合创建的(比本示例中的复杂得多)。

如何将以下示例转换为Flux,以便将我的结果流式传输,而不必在内存中聚合之前的所有项目?

@RestController
public class BookingInfoServlet {
    @Autowired
    private JdbcTemplate jdbc;

    @GetMapping(value = "/export", produces = APPLICATION_JSON_VALUE)
    public List<Item> export(String productType) {
        List<Item> list = new ArrayList<>();

        for (int i = 0; i < jdbc.count(); i++) {
            List<String> refIds = jdbc.queryForList("SELECT ref_id FROM products where type = ? LIMIT 1000 OFFSET = ?", String.class, productType, i);
            for (String id : refIds) {
                Map map = jdbc.queryForMap("SELECT <anything> ... where some_id = ?, id);
                Item item = new Item();
                item.setName(map.get("name"));
                item.setCode(map.getCode("code"));
                item.set...
                list.add(item);
            }

            //TODO how to convert to Flux here and already send the chunks back into the stream?
        }

        return list; //TODO how to convert to Flux?
    }
}

第一个问题:这里我首先将第一个查询的所有结果提取到内存中,然后在内存中迭代并形成我所有的Items,然后返回整个列表。

因此我试图返回Flux&lt;Item&gt;。但是:使用JdbcTemplate 时,我现在如何才能准确返回助焊剂?

由于没有异步mysql java 驱动程序,我可能必须将数据库查找分页为 1000 个块,然后准备 1000 个项目并将它们流式传输回客户端。然后获取接下来的 1000 个项目。但是我怎样才能让它们直接进入流?

【问题讨论】:

  • 我以为我做到了。我的问题是:如何将准备好的项目块列表发送回Flux&lt;Item&gt; 流,以便客户端始终以块的形式接收响应。它不一定是 1000 个块,也可以是一个一个。

标签: java spring spring-mvc spring-webflux reactive


【解决方案1】:
  public Flux<Item> export(String productType) {
    int pageSize = 1000;
    int count = jdbc.count();
    return Flux.range(0, count / pageSize) //page numbers
        .flatMapIterable(pageNumber ->
            jdbc.queryForList("SELECT ref_id FROM products where type = ? LIMIT ? OFFSET = ?",
                String.class,
                productType,
                pageSize,
                pageNumber * pageSize))
        .map(id -> {
          Map map = jdbc.queryForMap("SELECT <anything> ... where some_id = ?", id);
          Item item = new Item();
          //
          //
          return item;
        });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 2018-11-28
    • 2021-12-02
    • 2020-01-28
    • 2019-01-11
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多