我的项目中使用eureka作为服务注册中心,eureka-server提供restful接口上传文件,api项目中需要使用openfegin调用erurka-server上传文件。其中遇到了很多坑,做下记录,方便后面查看。
首先在api中需要引入openfegin的jar网上在使用feginClient时候,有的引用openFegin,有的会引用Fegin。具体两个区别是:
Fegin
1.Feign是Spring Cloud组件中的一个轻量级RESTful的HTTP服务客户端,有自己的一套注解;
2.Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务;
3.Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。
官网参考文档地址:https://github.com/OpenFeign/feign
openFegin
OpenFeign是Spring Cloud 在Feign的基础上支持了Spring MVC的注解,如@RequesMapping等
具体代码
1.引入的jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这里有我遇到的第一个坑,是没有引入spring-boot-starter-web,导致controller中接收不到文件,这个是耗费时间最长的。。。还有网上说要引入feign-form,feign-form-spring这些jar,你仔细去看openfegin中,人家都引入了,所以不需要引入。引入后记得在启动类中加入@EnableFeignClient,也可以使用basePackages = {“com.detection.service”})指定具体service的扫描包。
2.api中的controller代码
这里用于提供restful类型接口,接收移动传过来的数据,并调用feignclient去调用eureka-server上传文件。
@RestController
@RequestMapping(value = "/upload")
public class FileUploader {
@Autowired
private FileUploadService fileUploadService;
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile(@RequestParam MultipartFile file){
System.out.println(file.getOriginalFilename());
return fileUploadService.uploadFile(file);
}
}
3.feginclient代码
这里需要注意接收文件需要用@RequestPart,需要在@RequestMapping中设置consumes用来限制Http请求的ContentType ,使用produces 用来限制Accept的文件类型。
@FeignClient(name = "service-provider")
public interface FileUploadService {
/**
* 新增监督抽样台账详情
* @param file
* @return
*/
@RequestMapping(value = "/upload/uploadFile", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String uploadFile(@RequestPart(value = "file") MultipartFile file);
}
4.eureka-server中的上传接口代码
这里和service一样,使用RequestPart和consumes ,produces 接收然后上传文件即可。
@RestController
@RequestMapping("/upload")
public class UploadFile {
/**
* 上传文件
* @param file
* @return
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile(@RequestPart(value = "file") MultipartFile file) {
//上传文件的具体实现。。。
}
}
}
需要限制文件大小时,在application.yml文件中设置下:
spring:
servlet:
multipart:
enabled: true
max-file-size: 200MB
max-request-size: 200MB
max-file-size和max-request-size设置-1时为不限制大小