Dragon

业精于勤荒于嬉

0%

Spring Cloud Feign 发送长文本失败问题

问题描述

  • 开发环境 spring boot + spring cloud ,微服务之间的互相调用使用的组件为 feign
  • 平时服务之间各种调用完全没问题,但是最近发现在微服务之间发送长文本时会出现失败
  • 在此记录一下解决方案,方便以后查看,同时也帮助遇到同样问题而抓耳挠腮的朋友提供一个解决方案

解决方案

引入依赖

  • 如果使用的是 feign
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>
    <!--需要引入 feign-form -->
    <dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>${version}</version>
    </dependency>
  • 如果使用的是 openfeign
    1
    2
    3
    4
    5
    <!--只需要引入 openfeign -->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    编写配置类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Configuration
    public class CoreFeignConfiguration {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;


    @Bean
    @Primary
    @Scope(SCOPE_PROTOTYPE)
    Encoder feignFormEncoder() {
    return new FormEncoder(new SpringEncoder(this.messageConverters));
    }
    }

    具体配置

  • 在涉及到长文本调用的FeignClient注解中配置configuration
    1
    @FeignClient(value = "service-name", fallback = Hystrix.class, configuration = CoreFeignConfiguration.class)
  • 在涉及到长文本调用的方法中配置consumes,并且参数需要使用@PathVariable注解
    1
    2
    @RequestMapping(value = "methodName", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    String entrance(@PathVariable("dataJson") String dataJson);