声明式服务调用 Spring Cloud Feign

对Spring Cloud Ribbon和Spring Cloud Hystrix在实践过程中,这两个框架的使用几乎是同时出现的,Spring Cloud Feign就是一个更高层次的封装来整合这两个基础工具以简化开发。它基于Netflix Feign实现,除了提供这两者的强大功能之外,它还提供了一种声明式的Web服务客户端定义的方式。Spring Cloud Feign在RestTemplate的封装基础上做了进一步封装,由它来帮助定义和实现依赖服务接口的定义,在Spring Cloud Feign的实现下,只需创建一个接口并用注解的方式来配置它,即可完成对服务提供方接口的绑定。Spring Cloud Feign具备可插拔的注解支持,包括Feign注解和JAX-RS注解,为了适应Spring用户,它在Netflix Feign基础上扩展了对Spring MVC注解的支持。

1. 快速集成 Spring Cloud Feign

基础服务搭建

  • eureka-server工程:服务注册中心

  • hello-service工程:服务提供者

  • Spring Cloud Feign Client服务搭建

    1. 创建Spring Boot 工程 feign-consumer

    2. 添加依赖: spring-cloud-starter-eureka-server, spring-cloud-starter-feign

    3. 配置指定服务注册中心,并定义自身服务名

    4. 使用@EnableFeignClients开启Spring Cloud Feign 的支持功能

    5. 定义HelloClient接口,使用@FeignClient注解指定服务名来绑定服务,使用SpringMVC注解绑定具体该服务提供的REST接口

      //www.1b23.com
      @FeignClient("hello-service")
      public interface HelloClient {
          
          @RequestMapping("/hello")
          String hello();
      }
      
    6. 在需要调用的地方使用@Autowired注入HelloClient实例,并调用该指定服务接口来向该服务发起/hello接口的调用

2. 参数绑定

  • 设置Request Header

    通过设置Feign拦截器统一设置token,需要实现Feign提供的一个接口 RequestInterceptor

    //www.1b23.com
    @Configuration
    public class FeignRequestInterceptor implements RequestInterceptor {
        
        @Override
        public void apply(RequestTemplate requestTemplate) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                if (null != request) {
                	//添加token
                    requestTemplate.header("Authorization", request.getHeader("Authorization"));
                }
            }
        }
    }
    

    自定义Feign配置覆盖默认配置

    //www.1b23.com
    @Configuration
    public class FeignConfiguration {
        
        @Bean
        public FeignRequestInterceptor feignRequestInterceptor() {
            return new FeignRequestInterceptor();
        }
        
        // 超时重试
        @Bean
        public Retryer feignRetryer() {
            return new Retryer.Default(100, 1000, 5);
        }
    }
    

    在定义各参数绑定时,@RequestParam@PathVariable等可以指定参数名称的注解,value属性不能缺少,在Feign中绑定参数必须通过value属性指明具体的参数名,否则抛出 IllegalStateException异常。

  • 接收对象类型请求响应体

    接收对象必须有默认的构造函数即无参构造器,否则Spring Cloud Feign 根据 JSON 字符串转换对象时抛出异常。

3. 配置

3.1 Ribbon配置

Spring Cloud Feign客户端负载均衡通过Spring Cloud Ribbon实现,可以直接通过配置Ribbon客户端的方式自定义各个服务客户端的调用参数。

  • 全局配置

    使用 ribbon.<key>=<value>的方式设置ribbon的各项参数,如

    ribbon.ConnectTimeout=500
    ribbon.ReadTimeout=5000
    
  • 指定服务配置

    针对各个服务客户端进行个性化配置的方式与全局配置相似,使用<client>.ribbon.<key>=<value>的方式设置。client可以使用@FeignClient注解中的name或value属性值来设置对应的ribbon参数,如

    HELLO-SERVICE.ribbon.ConnectTiomeout=500
    HELLO-SERVICE.ribbon.ReadTimeout=5000
    HELLO-SERVICE.ribbon.OkToRetryOnAllOperations=true
    HELLO-SERVICE.ribbon.MaxAutoRetriesNextServer=2  // 尝试更换实例次数
    HELLO-SERVICE.ribbon.MaxAutoRetries=1  // 尝试访问首选实例次数
    
  • 重试机制

    Spring Cloud Feign中默认实现了请求的重试机制,上面对于HELLO-SERVICE客户端的配置就是对请求超时及重试机制配置的详情。

3.2 Hystrix配置

Spring Cloud Feign 还引入了服务保护与容错的工具Hystrix。默认情况Spring Cloud Feign会为所有Feign客户端的方法都封装到Hystrix命令中进行服务保护。

  • 全局配置

    使用hystrix.command.default.<key>=<value>的方式配置hystrix各项参数,如

    hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
    
  • 禁用 Hystrix

    1. 全局禁用

      feign.hystrix.enabled=false
      
    2. 针对指定服务禁用Hystrix

      构建关闭Hystrix配置类

      //www.1b23.com
      @Configuration
      public class DisableHystrixConfiguration {
          
          @Bean
          @Scope("prototype")
          public Feign.Builder feignBuilder() {
              return Feign.builder();
          }
      }
      

      @FeignClient注解中通过configuration参数引入配置类

      @FeignClient(name = "HELLO-SERVICE", configuration = DisableHystrixConfiguration.class)
      public interface HelliClient {
      
  • 指定命令配置

    使用hystrix.command.作为前缀,默认情况下采用Feign客户端中的方法名作为标识。

    如配置/hello接口的熔断超时时间:

    hystrix.command.hello.execution.isolation.thread.timeoutInMilliseconds=5000
    
    wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==
  • 服务降级配置

    1. 为Feign客户端的定义接口HelloService实现一个具体的实现类HelloServiceFallback

      @Component
      public class HelloServiceFallback implements HelloService {
      
    2. 在服务绑定接口中通过@FeignClient注解的fallback属性来指定对应的服务降级实现类

      @FeignClient(name="HELLO-SERVICE", fallback=HelloServiceFallback.class)
      public interface HelloService {

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值