猿问

如何在 Spring 中将 JdbcTemplate 转换为 Flux?

我有一个返回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?

    }

}

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


因此,我试图返回Flux<Item>。但是:我现在如何才能在使用时准确地返回通量JdbcTemplate?


由于没有异步mysqljava 驱动程序,我可能必须对数据库查找进行分页,例如 1000,然后准备 1000 个项目并将它们流回客户端。然后获取下 1000 个项目。但是我怎样才能让他们直接进入流呢?


料青山看我应如是
浏览 99回答 1
1回答

一只甜甜圈

&nbsp;public Flux<Item> export(String productType) {&nbsp; &nbsp; int pageSize = 1000;&nbsp; &nbsp; int count = jdbc.count();&nbsp; &nbsp; return Flux.range(0, count / pageSize) //page numbers&nbsp; &nbsp; &nbsp; &nbsp; .flatMapIterable(pageNumber ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jdbc.queryForList("SELECT ref_id FROM products where type = ? LIMIT ? OFFSET = ?",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.class,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; productType,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageSize,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageNumber * pageSize))&nbsp; &nbsp; &nbsp; &nbsp; .map(id -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Map map = jdbc.queryForMap("SELECT <anything> ... where some_id = ?", id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Item item = new Item();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return item;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答