眾所周知,Spring cloud gateway基於webflux響應式程式設計模式實現,那麼我們如何在webflux模式下把檔案上傳到阿里雲、騰訊雲等第三方雲服務呢?下面以阿里云為例,我們通過Mendmix檔案上傳元件實現上述需求。
引入依賴
<dependency>
<groupId>com.mendmix</groupId>
<artifactId>mendmix-cos-adapter</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.11.3</version>
</dependency>
新增配置
#aliyun OSS
mendmix.cos.adapter.type=aliyun
mendmix.cos.adapter.accessKey=5tHzzxhTs45tbUrKgTHYxxxx
mendmix.cos.adapter.secretKey=aIDWMP2pbvFjML7tYAzfPXXXXXXX
mendmix.cos.adapter.regionName=cn-guangzhou
然後就是貼程式碼了
@RestController
@RequestMapping(GatewayConstants.PATH_PREFIX)
public class CommonController {
@Autowired(required = false)
private CosProvider cosProvider;
@PostMapping("file/upload")
@ResponseBody
@ApiMetadata(actionName = "上傳檔案",permissionLevel = PermissionLevel.LoginRequired,requestLog = false)
public Mono<WrapperResponse<CUploadResult>> upload(ServerHttpRequest request,@RequestPart("file") FilePart filePart) {
Flux<DataBuffer> bufferFlux = filePart.content();
Mono<WrapperResponse<CUploadResult>> mono;
mono = bufferFlux.map(dataBuffer -> dataBuffer.asInputStream()) //
.reduce(SequenceInputStream::new) //
.flatMap(inputStream -> {
try {
byte[] bytes = IOUtils.toByteArray(inputStream);
CUploadResult result = cosProvider.upload(new CUploadObject(bytes, null));
return Mono.just(new WrapperResponse<>(result));
} catch (IOException e) {
e.printStackTrace();
return Mono.just(new WrapperResponse<>(500,"上傳失敗"));
}
});
return mono;
}
}
這樣就大功告成了。
Mendmix定位是一站式分散式開發架構開源解決方案及雲原生架構技術底座。Mendmix提供了資料庫、快取、訊息中介軟體、分散式定時任務、安全框架、閘道器以及主流產商雲服務快速整合能力。基於Mendmix可以不用關注技術細節快速搭建高併發高可用基於微服務的分散式架構。