zoukankan      html  css  js  c++  java
  • springcloud(九)-Feign使用Hystrix

    前言

    上一篇我们使用注解@HystrixCommond的fallbackMethod属性实现回退。然而,Feign是以接口形式工作的,它没有方法体,上一篇讲解的方式显然不适用于Feign。

    那么Feign要如何整合Hystrix呢?不仅如此,如何实现Feign的回退。

    在springcloud中,为Feign添加回退更加简单。事实上,springcloud默认已为Feign整合了Hystrix,要想为Feign打开Hystrix支持,只需要设置feign.hystrix.enabled=true即可。

    编码

    1.复制项目microservie-consumer-movie-feign,将ArtifactId修改为microservice-consumer-movie-feign-hystrix-fallback.

    2.在application.yml中添加feign.hystrix.enabled: true,从而开启Feign的Hystrix支持。

    server:
      port: 8082
    eureka:
      client:
        serviceUrl:
          defaultZone: http://localhost:8083/eureka/
      instance:
        prefer-ip-address: true
    spring:
      application:
        name: microservice-consumer-movie
    feign:
      hystrix:
        enabled: true

    3.将之前编写的Feign接口修改成如下内容:

    @FeignClient(name = "microservice-provider-user",fallback = FeignClientFallback.class)
    public interface UserFeignClient {
        @RequestMapping(value="/{id}",method = RequestMethod.GET)
        public User findById(@PathVariable("id") Long id);
    }
    @Component
    class FeignClientFallback implements UserFeignClient{
        public User findById(Long id) {
            User user = new User();
            user.setId(-1L);
            user.setUsername("默认用户");
            return user;
        }
    }

    由代码可知,只需使用@FeignClient注解的fallback属性,就可为指定名称的Feign客户添加回退。

    测试

    启动microservice-discovery-eureka.

    启动microservice-provider-user.

    启动microservice-consumer-movie-feign-hystrix-fallback.

    访问http://localhost:8082/user/1,可正常获得结果。

    {"id":1,"username":"account1","name":"张三","age":20,"balance":98.23}

    停止microservice-provider-user.

    再次访问http://localhost:8082/user/1,可获得如下结果。说明当用户微服务不可用时,进入了回退的逻辑。

    {"id":-1,"username":"默认用户","name":null,"age":null,"balance":null}

    补充:在springcloud Dalston之前的版本中,Feign默认开启Hystrix支持,无需设置feign.hystrix.enabled=true.从springcloud Dalston版本开始,Feign的Hystrix支持默认关闭,需要手动设置开启。

    由于代码过于简单,这里就不提交源码了。

  • 相关阅读:
    Intent
    What should we do next in general after collecting relevant data
    NOTE FOR Secure Friend Discovery in Mobile Social Networks
    missing pcap.h
    after building Android Source code
    plot point(one column)
    When talking to someone else, don't infer that is has been talked with others at first. It may bring repulsion to the person who is talking with you.
    进程基本知识
    Python input和raw_input的区别
    强制 code review:reviewboard+svn 的方案
  • 原文地址:https://www.cnblogs.com/fengyuduke/p/10792220.html
Copyright © 2011-2022 走看看