SpringCloud之Hystrix

Hystrix理解

熔断器本身是一种开关装置,用于在电路上保护线路过载。当线路中有电器发生短路时,熔断器能够及时切断故障电路,防止发生过载、发热甚至起火等严重后果。这种保护机制被借鉴到分布式系统的设计中,形成了类似Hystrix中的熔断器功能。熔断器在分布式系统中的作用主要是快速失败并返回错误,避免因为某个服务的故障导致整个系统的崩溃。

一、服务熔断

解决的问题
解决服务雪崩效应

1、导入hystrix依赖

<!--        熔断器 hystrix-->
 <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 </dependency>

2、使用服务熔断机制

在服务提供者基础上添加服务熔断机制,提供者=>这里!!!

3、控制层部分代码


@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    @GetMapping("/dept/get/{id}")
    // 使用@HystrixCommand注解标记get方法,并指定fallback方法
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public Dept get(@PathVariable("id") Long id){
        Dept dept = deptService.queryById(id);
        if( dept == null ){
            throw  new RuntimeException("id=>"+id+",不存在该用户信息,或信息无法找到");
        }
        return dept;
    }

    // 备选方案
    public Dept hystrixGet(@PathVariable("id") Long id){
        Dept dept = new Dept();
        dept.setDeptno(id)
                .setDname("id=>"+id+",不存在该用户信息")
                .setDb_source("no this database in MySQL");
        return dept;
    }
}

4、Hystrix服务提供者启动类

@EnableCircuitBreaker 开启熔断服务

@SpringBootApplication
@EnableEurekaClient  // 自动在服务启动后自动注册到Eureka中
@EnableCircuitBreaker // 熔断支持
public class SpringBootProviderHystrixApplication_8001 {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootProviderHystrixApplication_8001.class,args);
    }
    // 下面的代码是固定的 配合监控使用
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        registration.addUrlMappings("/actuator/hystrix.stream");
        return registration;
    }
}

5、测试结果

启动3个eureka服务、3个提供者服务、1个消费者服务,只是参考也可以不启动这么多服务,也可以使用单机版。

在这里插入图片描述

启动服务

客户端请求访问一个数据库不存在的信息http://localhost/consumer/dept/get/11,使用的是集群服务,其中只有一个服务实现了熔断机制,总有一次会显示提示信息。其它两次提供者服务没有使用熔断机制是不会返回信息的。
在这里插入图片描述

二、服务降级

和客户端有关,服务端提供降级信息。

使用场景

使用Hystrix服务降级使用场景,当故障服务调用失败或超时时,Hystrix会快速返回这个备选响应,而不是让调用方长时间等待或抛出异常。这样,即使部分服务出现问题,整个系统依然能够正常运行,用户也能够得到及时的反馈,而不是无休止的等待。

在这里插入图片描述

创建降级处理工厂类

1、实现FallbackFactory 降级处理工厂类

// 服务降级
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory {
    // 也就是放回整个类
    @Override
    public DeptClientService create(Throwable throwable) {
        return new DeptClientService() {
            @Override
            public Dept get(Long id) {
                return new Dept().setDeptno(id)
                        .setDname("id=>"+id+"没有找到该信息 ,这是客户端提供的降级信息,这个服务现在已经被关闭")
                        .setDb_source("没有可获得的数据");
            }

            // 下面的方法也需要返回结果,懒没有实现
            @Override
            public List<Dept> getAll() {
                return null;
            }

            @Override
            public boolean add(Dept dept) {
                return false;
            }
        };
    }
}

2、使用Feign来调用Http请求

@FeignClient注解添加 fallbackFactory 参数返回之前创建的DeptClientServiceFallbackFactory类

// fallbackFactory 放回工厂,降级操作
@FeignClient(name = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {

    @GetMapping("/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> getAll();

    @PostMapping("/dept/add")
    public boolean add(Dept dept);
}

3、消费者客户端application.yml

# 核心配置展示

# feign 配置 在客户端
feign:
  hystrix:
    enabled: true # feign 开启服务降级

4、Feign客户端启动类

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.jyl.springcloud"}) // 扫描到springcloud-api中的sercie包下的DeptClientService接口
public class DeptConsumer_Feign_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_Feign_80.class,args);
    }
}

5、测试结果

当将所有的提供者服务关闭之后。

在这里插入图片描述

服务端提供者关闭

客户端访问http://localhost/consumer/dept/get/1 ,依旧可以返回内容,不会服务崩掉。

在这里插入图片描述

三、监控页面

项目名称:springcloud-consumer-hystrix-dashboard

1、导入依赖

 <!--        熔断 hystrix-->
 <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 </dependency>

 <!-- dashboard       -->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
     <version>1.4.6.RELEASE</version>
 </dependency>

服务端提供者必须导入下面依赖:

 <!--        解决 eureka Status  actuator/info 完善监控信息-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>

2、application.yml

修改端口号,避免端口冲突

server:
  port: 9001

3、客户端启动类

@EnableHystrixDashboard开启监控

@SpringBootApplication
@EnableHystrixDashboard // 开启监控
public class DeptConsumerDashboard_9001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumerDashboard_9001.class,args);
    }

}

4、服务端提供者启动类

需要在服务端启动类中添加ServletRegistrationBean

@SpringBootApplication
@EnableEurekaClient  // 自动在服务启动后自动注册到Eureka中
@EnableDiscoveryClient // 服务发现
@EnableCircuitBreaker // 熔断支持
public class SpringBootProviderHystrixApplication_8001 {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootProviderHystrixApplication_8001.class,args);
    }
    // 下面的代码是固定的
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        registration.addUrlMappings("/actuator/hystrix.stream");
        return registration;
    }
}

5、测试结果

访问http://localhost:9001/hystrix

在这里插入图片描述

hystrix监控界面

点击Monitor Stream按钮实时监控服务端提供者localhost:8001
监控请求信息
在这里插入图片描述

hystrix监控面板

七色一圈一线

  • 七色
    在这里插入图片描述

  • 一圈
    实心圆:公有两种含义,他通过颜色的变化代表了实例的健康程度它的健康程度从绿色<黄色<橙色<红色递减
    该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大,该实心圆就越大,所以通过该实心圆的展示,就可以在大量的实例中快速发现故障实例和高压力实例。

  • 一线
    曲线:用来记录2分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势! I

如果不清楚请看B站大佬视频=>狂神说

  • 34
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小江||小廖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值