Spring Cloud中使用Hystrix实现断路器

1.为什么要使用Hystrix

多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又在调用其他的微服务,这就是所谓的“扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,那么对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,这就是所谓的“雪崩效应”。

2.Hystrix的概述

出现这种“雪崩效应”肯定是可怕的,在分布式系统中,我们无法保证某个服务一定不出问题,Hystrix 可以解决。

Hystrix 是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多服务无法避免会调用失败,比如超时、异常等等,Hystrix能够保证在一个服务出现问题的情况下,不会导致整体服务的失败,避免级联故障,以提高分布式系统的弹性。

3.Hystrix 的使用

3.1在请求的接口类使用hystrix的服务熔断

1.添加依赖

order-service

        <!-- 引入spring cloud整合的hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.10.RELEASE</version>
        </dependency>

2.激活hystrix

@EnableHystrix
public class OrderServiceApplication {

3.降级处理

(1)在OrderController添加降级方法

/**
 * 降级方法
 *  和需要受到保护的方法的 返回值一致、方法参数一致
 */
public Product orderFallBack(Long id){
    Product product = new Product();
    product.setProductName("触发降级方法");
    return product;
}

(2)在需要受到保护的方法上使用@HystrixCommand配置

    @HystrixCommand(fallbackMethod = "orderFallBack")
    @GetMapping(value = "/buy/{id}")
    public Product findById(@PathVariable Long id) {
        return productFeignClient.findById(id);

(3)模拟网络延迟(在product-service)

        try {
            Thread.sleep(2000l);//模拟请求网络延迟
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

(4) Hystrix配置(order-service的application.yml中)

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: ExecutionIsolationStrategy.SEMAPHORE #信号量隔离
          #strategy: # ExecutionIsolationStrategy.THREAD 线程池隔离
          thread:
            timeoutInMilliseconds: 2000 #默认的连接超时时间1秒,若1秒没有返回数据,自动的触发降级逻辑
      circuitBreaker:
        requestVolumeThreshold: 5 #触发熔断的最小请求次数,默认20 /10秒
        sleepWindowInMilliseconds: 10000 #熔断多少秒后去尝试请求 默认 5   打开状态的时间
        errorThresholdPercentage: 50 #触发熔断的失败请求最小占比,默认50%

(5) 测试 

启动eureka、product、order服务  http://localhost:9002/order/buy/1

因为模拟网络延迟是2s 加上数据库的请求会大于2s所以会触发降级方法 现在将线程超时时间改为6s再看看结果

正常访问到数据

4.统一的降级方法

如果每个方法都写一个降级方法,方法多的时候,很麻烦,可以统一指定降级方法。

(1)修改OrderController类,添加统一降级方法

	/**
     * 指定统一的降级方法
     *   注意方法没有参数
     */
    public Product defaultFallBack(){
        Product product = new Product();
        product.setProductName("触发统一的降级方法");
        return product;
    }

(2)在OrderController类上方添加@DefaultProperties注解

@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController {

(3)修改findById方法上方的@HystrixCommand注解,将@HystrixCommand(fallbackMethod = "orderFallBack")改为@HystrixCommand

(4)6s>2s

(5)测试

3.2 Feign结合hystrix服务熔断

1.复制服务

复制order-service得到order-service-feign_hystrix(注意:在idea里直接复制会有问题。在文件资源管理器里复制才不会出现问题。)

2.feign中开启hystrix及相关配置

修改order-service-feign_hystrix服务application.yml在Fegin中开启hystrix

# 在feign中开启hystrix熔断
feign:
  circuitbreaker:
    enabled: true

修改 端口号及服务名称

server:
  port: 9003
spring:
  application:
    name: service-order-feign_hustrix

hystrix设置

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2000 #默认的连接超时时间1秒,若1秒没有返回数据,自动的触发降级逻辑
      circuitBreaker:
        enabled: true
        requestVolumeThreshold: 5
        errorThresholdPercentage: 10
        sleepWindowInMilliseconds: 10000

3.接口实现类中实现降级逻辑

编写接口实现类,编写熔断降级方法

package org.example.order.feign;
 
import org.example.order.entity.Product;
import org.springframework.stereotype.Component;
 
@Component
public class ProductFeginClientCallBack implements ProductFeignClient{
    /**
     * 降级方法
     */
    @Override
    public Product findById(Long id) {
        Product product = new Product();
        product.setProductName("触发Feign熔断降级方法");
        return product;
    }
}

4.接口注解声明降级类

修改ProductFeignClient接口

@FeignClient添加使用降级的方法所在的类 fallback = ProductFeginClientCallBack.class

@FeignClient(name = "service-product", fallback = ProductFeginClientCallBack.class)
public interface ProductFeignClient {
 
    /**
     * 配置需要调用的微服务接口
     * @return
     */
    @RequestMapping(value = "/product/{id}", method = RequestMethod.GET)
    Product findById(@PathVariable("id") Long id);
}

5.注释或删除之前的Hystrix相关代码

注释或删除启动类的@EnableHystrix注解

6.测试

启动eureka、product、order(9003)服务 http://localhost:9003/order/buy/1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值