众所周知,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可以不用关注技术细节快速搭建高并发高可用基于微服务的分布式架构。