场景:
跨服务调用文件上传接口
技术栈:Feign + nacos
报错:
feign.codec.EncodeException: Error converting request body
解决方案:
step1:添加pom依赖
<!--这里我使用nacos注册中心,如果没有使用可以不用nacos-discovery-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
step2:添加配置类 FeignMultipartSupportConfig.java
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.*;
import org.springframework.web.client.RestTemplate;
@Configuration
public class FeignMultipartSupportConfig {
@Bean
@Primary
@Scope("prototype")
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new RestTemplate().getMessageConverters());
}
}));
}
@Bean
public feign.Logger.Level multipartLoggerLevel() {
return feign.Logger.Level.FULL;
}
}
step3:编写Feign Client
import com.hzd.config.FeignMultipartSupportConfig;
import com.privatecloud.core.dto.JsonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
/**
* 注意点
* 1:configuration = FeignMultipartSupportConfig.class
* 2.consumes = MediaType.MULTIPART_FORM_DATA_VALUE
*/
@FeignClient(value = "baseserver",configuration = FeignMultipartSupportConfig.class)
public interface BaseserverClient {
/**
* 文件上传至阿里云
* @param file
* @param imei
* @param sysDictItemId
* @return
*/
@PostMapping(value = "/file/image/uplode", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
JsonResult<String> upload(@RequestPart MultipartFile file);
}
step4:调用
@Api(tags = "植物智能管理", value = "植物库")
@RestController
@RequestMapping("/plant/AI")
@Slf4j
public class PlantAIController {
@Autowired
private BaseserverClient baseserverClient;
@PostMapping("/recognition")
public void test(@RequestPart(value = "file", required = false) MultipartFile file){
baseserverClient.upload(file);
}
}