feign 初体验

作者: 木山手札 | 来源:发表于2020-02-08 15:18 被阅读0次

所需服务

  • 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

相关文章

网友评论

    本文标题:feign 初体验

    本文链接:https://www.haomeiwen.com/subject/dusixhtx.html