使用openFegin調用其他服務的上傳文件接口

我的項目中使用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時爲不限制大小

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章