springcloud(Hystrix)四

服务熔断(在服务端)

  • 新建一个springcloud-provider-dept-hystrix-8001;
  • 添加hystrix依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
  • 修改application.yml的instance-id为springcloud-provider-dept-hystrix-8001
    image
  • 在DeptController中编写熔断方法(就是如果查询不存在的id,那么就会走熔断方法)
    image
  • 在主启动类上添加对hystrix的支持@EnableCircuitBreaker//添加对熔断的支持
  • 在eureka集群的基础上再启动springcloud-provider-dept-hystrix-8001,测试访问
    如果查询数据库存在的id,那么
    image
    如果查询数据库不存在的id,那么
    image
    成功触发了熔断回调方法。

///////////////////////////////////////////////////////////////////////////////////////////
如果左下角显示的是类似localhost这样的,想显示IP地址,像图这样,可以这样设置
image
image

服务降级(在客户端)

  • 在springcloud-api里的service新建一个类DeptClientServiceFallbackFactory实现FallbackFactory,重写create,写一些返回前台的提示信息
    image
  • 在DeptClientService添加引用DeptClientServiceFallbackFactory该类
    image
  • 在springcloud-consumer-dept-feign-80中的application.yml添加降级配置
    image
  • 测试访问
    正常可以查询出数据
    image
    关掉服务端即8001,再次访问,虽然查询不到数据,但是显示友好信息,调用的是DeptClientServiceFallbackFactory
    image

Dashboard流监控(监控服务状态)

  • 新建springcloud-consumer-hystrix-dashboard,在consumer依赖的基础上再添加hystrix依赖;
<!--hystrix依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
  • 添加application.yml(不配置eureka会报错)
server:
  port: 9001
eureka:
  client:
    register-with-eureka: false #不向eureka注册自己
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  • 添加主启动类DeptConsumerDashboard_9001
    image
  • 测试dashboard是否搭建成功,启动7001,7002,7003,再启动dashboard
    访问http://localhost:9001/hystrix
    image
  • 下面启动springcloud-provider-dept-hystrix-8001,但是之前需要检测几个步骤
    1、pom.xml是否有监控依赖
    image
    2、在主启动类添加一个hystrix相关的servlet
    image
    3、检查一下DeptController,只能监控/get/id
    image
    3、可以启动springcloud-provider-dept-hystrix-8001了
    4、访问一下接口http://localhost:8001/dept/get/2 查看是否可以查出来
    image
    5、访问http://localhost:8001/actuator/hystrix.stream 查看是否是通的
    image
    6、在dashboard输入需要监控的服务,点击Monitor Stream
    image
    image
    7、不断访问http://localhost:8001/dept/get/2
    image

dashboard界面详解

image
image
image
image
image

原文地址:https://www.cnblogs.com/kaka-qiqi/p/14624673.html