Spring Cloud-09Feign使用Hystrix

版权声明:【show me the code ,change the world】 https://blog.csdn.net/yangshangwei/article/details/85042142

版本说明

先说下使用的spring cloud和spring boot的版本
在这里插入图片描述

Disable HystrixCommands For FeignClients By Default
https://github.com/spring-cloud/spring-cloud-netflix/issues/1277


新建子module

父工程microservice-spring-cloud右键新建Maven Module 命名为:micorservice-consumer-movie-feign-hystrix ,为了简单我们把micorservice-consumer-movie-feign的内容copy到该子模块,修改下application.yml中的spring.application.name即可。


application.yml中开启Hystrix

server:
  port: 7901

spring: 
  application:
    name: micorservice-consumer-movie-feign-hystrix  
#eureka
eureka: 
  client:
    service-url:
      defaultZone: http://artisan:artisan123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}

# Disable HystrixCommands For FeignClients By Default
# https://github.com/spring-cloud/spring-cloud-netflix/issues/1277    
feign:
  hystrix:
    enabled: true

如果是application.property ,请设置 feign.hystrix.enabled=true


修改Feign接口

使用fallback属性指定回退类

在这里插入图片描述

回退类 也需要实现上面的接口,同时需要标注@Component让其成为受spring管理的bean
在这里插入图片描述


测试

  1. 启动microservice-discovery-eureka,注册中心
  2. 启动micorservice-provider-user,服务提供者
  3. 启动micorservice-consumer-movie-feign-hystrix,服务消费者开启了Hystrix

访问http://localhost:8761/ 确认下服务已经注册成功。

在这里插入图片描述

访问 http://localhost:7901/movie/1

{"id":1,"username":"artisan1","name":"小工匠一","age":10,"balance":100.00}

功能正常,OK。

现在停掉micorservice-provider-user

在这里插入图片描述

访问 http://localhost:7901/movie/1 ,进入了回退方法

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

再次启动 micorservice-provider-user
在这里插入图片描述

再次访问 http://localhost:7901/movie/1

{"id":1,"username":"artisan1","name":"小工匠一","age":10,"balance":100.00}

功能正常,OK。


代码

https://github.com/yangshangwei/SpringCloudMaster

猜你喜欢

转载自blog.csdn.net/yangshangwei/article/details/85042142