feign 初体验

所需服务

  • eureka 注册中心 2台(高可用)
  • foo-service 暴露服务接口 2台(负载均衡)
  • invoke-service 充当服务调用者 1台
  • 具体版本和环境配置

配置

  • 引入相关依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 定义feign接口
@FeignClient("foo-service")
@RequestMapping("/foo")
public interface FooServiceFeign {
    @RequestMapping("/echo")
    String echo(@RequestParam("message") String message);
}
  1. @FeignClient("foo-service") 声明调用的服务名称
  2. 接口可以使用springmvc相关注解
  • 启动类使用@EnableFeignClients开启feign相关功能
  • Controller中使用定义好的FooServiceFeign接口进行调用
  • foo-service暴露接口时最好将端口号作为返回值返回,这样能方便的看到负载均衡的效果
@Value("${server.port}")
private int serverPort;

@RequestMapping("/echo")
public String echo(String message) {
    System.out.println("FooController.echo "+System.currentTimeMillis());
    return "foo-service echo {" + message + "} from serverPort="+serverPort;
}

其它配置

feign:
  compression: # reqeust、response开启压缩
    request:
      enabled: true
      mime-types: # 设置压缩的数据类型,以下是默认值
        - text/html
        - application/xml
        - application/json
      min-request-size: 1024 # 超过该值触发压缩,默认2048
    response:
      enabled: true
  client:
    config:
      foo-service: # 对应服务名称
        loggerLevel: FULL

logging:
  level:
    org.invoke.feign.FooServiceFeign: debug
  1. 针对feign request、response可以开启压缩
  2. feign打印详细日志时,定义feign接口所在的包也必须同时开启debug模式

配置类

  1. FeignClientProperties -> feign.client
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容