本篇文章给大家分享的是有关利用Feign怎么实现一个跨服务文件上传下载功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1、跨服务文件上传,目前feign不支持调用文件上传接口,需要自行配置来满足feign的调用方式
①.首先需要在pom文件里添加feign依赖
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.2.2</version> </dependency>
②.上传的接口
@FeignClient(value = "fdn-storage", configuration = {FileFeignConfig.class}) public interface FileClient { String PREFIX_PATH = "/oss/files"; /** * 上传存储文件 * @param file * @return * @throws IOException */ @PostMapping(value = PREFIX_PATH + "/", consumes = MULTIPART_FORM_DATA_VALUE) FeignResult<FileEntity> save(@RequestPart(value = "file") MultipartFile file) throws IOException; }
③.添加配置来满足feign的调用
@Configuration public class FileFeignConfig { @Autowired private ObjectFactory<HttpMessageConverters> messageConverters; @Bean @Primary @Scope("prototype") public Encoder feignEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); } @Bean public feign.Logger.Level multipartLoggerLevel() { return feign.Logger.Level.FULL; } }
④.外部服务的controller层调用
public class TestController extends BaseRestController { @Autowired FileClient client; /** * 上传文件 **/ @PostMapping(value = "/" , consumes = MULTIPART_FORM_DATA_VALUE) public FileEntity save(@RequestPart(value = "file") MultipartFile file) throws IOException { FileEntity fileEntity = client.save(file).getData(); return fileEntity; } }
到此位置就可以上传成功了
2、跨服务的文件下载
①.下载的接口(也是写在public interface FileClient),是用feign.Response来作为返回值的
/** * 下载文件 * @param id * @return * @throws IOException */ @GetMapping(value = PREFIX_PATH + "/{id}/data") Response download(@PathVariable("id") String id) throws IOException;
②.外部服务的controller层调用
/** *由id下载存储的文件 */ @GetMapping(value = "/{id}/data") public void downloadFile(@PathVariable String id, HttpServletResponse servletResponse) throws IOException { Response response = client.download(id); Response.Body body = response.body(); for(Object key : response.headers().keySet()){ List<String> kList = (List)response.headers().get(key); for(String val : kList){ servletResponse.setHeader(StringUtils.toString(key), val); } } try(InputStream inputStream = body.asInputStream(); OutputStream outputStream = servletResponse.getOutputStream() ){ byte[] b = new byte[inputStream.available()]; inputStream.read(b); outputStream.write(b); outputStream.flush(); }catch (IOException e){ throw new RestException("IO流异常", e); } }
以上就是利用Feign怎么实现一个跨服务文件上传下载功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。