使用webflux提升数据导出效率
生活随笔
收集整理的這篇文章主要介紹了
使用webflux提升数据导出效率
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
序
本文主要研究一下如何使用webflux提升數據導出效率
傳統導出
@GetMapping("/download-old")public ResponseEntity<Resource> downloadInOldWays(){return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=demo.xls").header("Accept-Ranges", "bytes").body(new ByteArrayResource(exportBytes(1000)));}public byte[] exportBytes(int dataRow){StringBuilder output = new StringBuilder();output.append(ExcelUtil.startWorkbook());output.append(ExcelUtil.startSheet());output.append(ExcelUtil.startTable());output.append(ExcelUtil.writeTitleRow(Sets.newHashSet("title","content")));IntStream.rangeClosed(1,dataRow).forEach(i -> {try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}output.append(ExcelUtil.writeDataRow(Lists.newArrayList("title"+i,"content"+i)));});output.append(ExcelUtil.endTable());output.append(ExcelUtil.endSheet());output.append(ExcelUtil.endWorkbook());return output.toString().getBytes(StandardCharsets.UTF_8);}這里模擬的是等所有數據都準備好了再導出,這種速度肯定慢,差不多需要等待100秒瀏覽器才能彈出下載框,如果前面有網關,很容易在網關那里超時了
webflux導出
@GetMapping("/download")public Mono<Void> downloadByWriteWith(ServerHttpResponse response) throws IOException {response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=demo.xls");response.getHeaders().add("Accept-Ranges", "bytes");Flux<DataBuffer> flux = excelService.export(1000);return response.writeWith(flux);}public Flux<DataBuffer> export(int dataRow){return Flux.create(sink -> {sink.next(stringBuffer(ExcelUtil.startWorkbook()));sink.next(stringBuffer(ExcelUtil.startSheet()));sink.next(stringBuffer(ExcelUtil.startTable()));//write title rowsink.next(stringBuffer(ExcelUtil.writeTitleRow(Sets.newHashSet("title","content"))));//write data rowIntStream.rangeClosed(1,dataRow).forEach(i -> {try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}sink.next(stringBuffer(ExcelUtil.writeDataRow(Lists.newArrayList("title"+i,"content"+i))));});sink.next(stringBuffer(ExcelUtil.endTable()));sink.next(stringBuffer(ExcelUtil.endSheet()));sink.next(stringBuffer(ExcelUtil.endWorkbook()));sink.complete();});}這里使用ReactiveHttpOutputMessage的writeWith(Publisher<? extends DataBuffer> body)方法,實現邊準備數據邊導出 等待十幾秒就彈下載框,之后就server端一邊輸出,瀏覽器一邊下載,100秒左右下載完畢
小結
兩種方法目前看來用時差不多,不過后者可以避免超時。當然使用傳統mvc也可以實現類似效果,就是拿到response的輸出流不斷地write和flush。不過webflux可以配合reactive的repository,實現端到端的reactive stream,同時也可以避免OOM。
轉載于:https://my.oschina.net/go4it/blog/1621396
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的使用webflux提升数据导出效率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为nginx创建windows服务自启动
- 下一篇: ionic实现下载文件并打开功能(fil