hystrix的服务降级和关于熔断的概念、使用等以及网关gateway的了解与使用

一、Hystrix的局部降级逻辑的处理方式

1.局部降级(提供方)

1)、在服务提供方的service里面 给指定的方法编写降级的方法,降级方法(逻辑)编写的原则是方法的形参和返回值必须要和被降级的方法保持一致。

@Service
public class PaymentService {
    @HystrixCommand(fallbackMethod = "handOk",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    })
    public String paymentInfo_Ok(Integer id){
        int i = 10/0;
        return "线程池:" + Thread.currentThread().getName() + "  ,paymentInfo_OK,id:" + id;
    }

    
     超时访问的方法
     
    @HystrixCommand(fallbackMethod = "handTimeOut",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_Timeout(Integer id){
        int interTime = 3;
        //int i = 10/0;
        try{
            TimeUnit.SECONDS.sleep(interTime);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + "  ,paymentInfo_Timeout,id:" + id + "耗时" + interTime + "秒钟";
        return "hello";
    }
    public String handTimeOut(Integer id){
        return "调用服务超时,请稍后再试!";
    }
    public String handOk(Integer id){
        return "服务器内部资源错误,请稍后再试!";
    }

3)、在启动类上开启服务熔断的功能 @SpringCloudApplication

//@SpringBootApplication
//@EnableDiscoveryClient
//@EnableCircuitBreaker
//这个注解包含上面三个注解
@SpringCloudApplication
public class HystrixPaymentApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixPaymentApplication.class,args);
    }

4)、将降级的逻辑应用在某个服务上

 @HystrixCommand(fallbackMethod="降级逻辑的方法名",commandProperties={
                        @HystrixProperties(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
                    })
                    public String timeout(){}

2.局部降级(提供方)

1)、在消费方的启动类上面开启熔断 @EnableCircuitBreaker

2)、在消费方的controller里面定义降级逻辑的方法。将降级逻辑应用在被降级的方法上面(实现的思路和上面一样)

二、全局降级处理方式

1.全局降级逻辑

1)、在消费方的启动类上面要加上一个@EnableCircuitBreaker

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker//开启熔断器
public class HystrixOrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixOrderApplication.class,args);
    }
}

2)、在消费方的controller里面,定义一个全局降级的方法。

//全局降级处理方法
    public String globalHandler(){
        return "这是全局处理降级逻辑的方法.......";
    }

3)、在controller上面 添加一个@DefaultProperties(defaultFallback = “handleAll”)注解

4)、在指定的被降级的方法上添加一个@HystrixCommand

5)、降级逻辑的优先级 局部的降级逻辑>全局的降级逻辑

@RestController
@DefaultProperties(defaultFallback = "globalHandler")
public class OrderController {
    @Autowired
    OrderHystrixClient orderHystrixClient;
    /*@HystrixCommand(fallbackMethod = "numberException", commandProperties = {
             //设置峰值,超过 1.5 秒,就会调用兜底方法
             @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value = "1500")
     })*/
    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id")Integer id){
        //int i = 100/0;

        return orderHystrixClient.ok(id);
    }
   /*@HystrixCommand(fallbackMethod = "handException", commandProperties = {
            //设置峰值,超过 1.5 秒,就会调用兜底方法
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })*/
    @HystrixCommand
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_Timeout(@PathVariable("id")Integer id){
        return orderHystrixClient.timeout(id);
    }

2.降级服务的抽取

1)、先将服务消费方关于降级处理的配置全部清除,在yml配置文件开启Feign基于对Hystrix的支持

# 用于服务降级 在注解@FeignClient 中添加 fallback 属性值
feign:
hystrix:
  enabled: true  # 在feign中开启 hystrix

2)、定义一个类实现Feign客户端接口

@Component
public class FallBackService implements OrderHystrixClient {
    @Override
    public String ok(Integer id) {
        return "进行paymentInfo_OK方法降级处理......";
    }

    @Override
    public String timeout(Integer id) {
        return "进行paymentInfo_Timeout方法降级处理";
    }
}

3)、修改Feign客户端接口

@Component
public class FallBackService implements OrderHystrixClient {
    @Override
    public String ok(Integer id) {
        return "进行paymentInfo_OK方法降级处理......";
    }

    @Override
    public String timeout(Integer id) {
        return "进行paymentInfo_Timeout方法降级处理";
    }
}

三、什么是熔断? 熔断有哪几种状态 断路器的工作原理

1.熔断

 1. 当用户访问某个服务,达到了最大的访问量之后,直接拒绝用户访问。

2.熔断三种状态

1.打开状态(open)、2.断开状态(close)、3.半开状态(half open) 

3. 断路器的工作原理

	统计用户在指定的时间范围(默认10s)之内的请求总数达到指定的数量之后,
	如果不健康的请求(超时、异常)占总请求数量的百分比(50%)
    达到了指定的阈值之后,就会触发熔断。触发熔断,断路器就会打开(open),此时所有请求都不能通过。在5s之后,断路器
    会恢复到半开状态(half open),会允许少量请求通过,如果这些请求都是健康的,那么断路器会回到关闭状态(close).如果
    这些请求还是失败的请求,断路器还是恢复到打开的状态(open).

四、如何开启熔断

1.首先在启动类上开启服务熔断 @EnableCircuitBreaker 开启服务熔断

2.service层的方法设置服务熔断

//服务熔断
    @HystrixCommand(fallbackMethod = "timeoutHandler", commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled", value="true"),  // 是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"),  //请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="10000"), // 时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="60"),  // 失败率达到多少后跳闸
            //整体意思:10秒内 10次请求,有6次失败,就跳闸
    })
    public String paymentCircuitBreaker(Integer id){
        //模拟发生异常
        if(id < 0){
            throw new RuntimeException("*****id,不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serialNumber;
    }

    public String timeoutHandler(Integer id){
        return "id不能为负数,请重试......";
    }

3.定义controller

//服务熔断
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id")Integer id){
    return paymentService.paymentCircuitBreaker(id);
}

4.使用XML的方式进行熔断的配置

           hystrix:
           command:
               default:
                circuitBreaker:
                 enabled: true
                  requestVolumeThreshold: 10
                    sleepWindowInMilliseconds: 10000
                      errorThresholdPercentage: 60

五、什么是网关? gateway 的核心概念

1.gateway网关

1)、 什么是 API 网关(API Gateway)

分布式服务架构、微服务架构与 API 网关
在微服务架构里,服务的粒度被进一步细分,各个业务服务可以被独立的设计、开发、测试、部署和管理。
这时,各个独立部署单元可以用不同的开发测试团队维护,可以使用不同的编程语言和技术平台进行设计,
这就要求必须使用一种语言和平 台无关的服务协议作为各个单元间的通讯方式。			 

2)、API 网关的定义

网关的角色是作为一个 API 架构,用来保护、增强和控制对于 API 服务的访问。
API 网关是一个处于应用程序或服务(提供 REST API 接口服务)之前的系统,用来管理授权、
访问控制和流量限制等,这样 REST API 接口服务就被 API 网关保护起来,对所有的调用者透明。
因此,隐藏在 API 网关后面的业务系统就可以专注于创建和管理服务,而不用去处理这些策略性的基础设施。

3)、Gateway是什么

Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,
Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。
Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代ZUUL,其不仅提供统一的路由方式,
并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

4)、 为什么用Gateway

Spring Cloud Gateway 可以看做是一个 Zuul 1.x 的升级版和代替品,比 Zuul 2 更早的使用 Netty 实现异步 IO,
从而实现了一个简单、比 Zuul 1.x 更高效的、与 Spring Cloud 紧密配合的 API 网关。
Spring Cloud Gateway 里明确的区分了 Router 和 Filter,并且一个很大的特点是内置了非常多的开箱即用功能,
并且都可以通过 SpringBoot 配置或者手工编码链式调用来使用。
比如内置了 10 种 Router,使得我们可以直接配置一下就可以随心所欲的根据 Header、或者 Path、
或者 Host、或者 Query 来做路由。
比如区分了一般的 Filter 和全局 Filter,内置了 20 种 Filter 和 9 种全局 Filter,
也都可以直接用。当然自定义 Filter 也非常方便。

2. gateway 的核心概念

在这里插入图片描述

六、如何简单使用gateway

1.首先创建cloud-gateway-gateway9527服务

2.引入POM依赖

<dependencies>
    <!--gateway-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!--eureka-client gateWay作为网关,也要注册进服务中心-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!-- gateway和web不能同时存在,即web相关jar包不能导入 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <groupId>com.jiyun.cloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

3.编写application.yml配置文件

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  ## GateWay配置
  cloud:
    gateway:
      routes:
      - id: payment_routh  # 路由ID , 没有固定的规则但要求唯一,建议配合服务名
        uri: http://localhost:8001  # 匹配后提供服务的路由地址
        predicates:
        - Path=/payment/**  # 断言,路径相匹配的进行路由

      - id: payment_routh2  # 路由ID , 没有固定的规则但要求唯一,建议配合服务名
        uri: http://localhost:8001  # 匹配后提供服务的路由地址
        predicates:
        - Path=/payment/lb/**  # 断言,路径相匹配的进行路由

# 注册进 eureka Server
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
    register-with-eureka: true
    fetch-registry: true

4.编写启动类

@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GatewayMain9527.class,args);
    }
}

5.启动8001服务以及9527进行测试

在这里插入图片描述

最终的出结论:我们使用网关,无需在访问我们的8001端口号进行访问,直接使用9527端口号访问即可
也是出于对8001服务的安全。主要通过9527服务中application.yml进行配置:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
一、Spring Cloud Hystrix 1. 什么是 Hystrix Hystrix 是一个延迟和容错库,用于隔离依赖服务的访问点,以防止这些依赖服务的故障导致雪崩效应。它提供了熔断、限流和降级等机制,保障了对依赖服务的访问。 2. Hystrix的核心概念 熔断:在一段时间内,如果服务的错误比例超过了设定的阈值,那么这个服务就会被熔断,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { int i = new Random().nextInt(10); if (i % 2 == 0) { throw new RuntimeException("error"); } return "success"; } public String fallbackMethod(){ return "fallback"; } ``` 限流:在一段时间内,如果服务的请求数量超过了设定的阈值,那么这个服务就会被限流,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000")}) public String method() { return "success"; } public String fallbackMethod(){ return "fallback"; } ``` 降级:在一段时间内,如果依赖服务不可用,那么就会调用预先备选的服务逻辑或返回预先设定的响应,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { return restTemplate.getForObject("http://service-provider/method", String.class); } public String fallbackMethod(){ return "fallback"; } ``` 3. Hystrix的集成 添加依赖 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> ``` 开启熔断 ``` @SpringBootApplication @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 添加注解 ``` @Service public class Service { @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { return "success"; } public String fallbackMethod() { return "fallback"; } } ``` 4. 测试 启动服务后,访问 http://localhost:8080/method,可以看到服务正常返回"success"。将calledOnce设置为false并再次访问该URL,可以看到服务返回"fallback"。 二、Spring Cloud Gateway 1. 什么是 Gateway Gateway 是 Spring Cloud 提供的一种 API 网关服务,基于 Spring 5.0、Spring Boot 2.0 和 Project Reactor 等技术开发。 2. Gateway 的三种机制 熔断:默认使用 Hystrix 进行熔断,示例代码: ``` spring.cloud.gateway.routes.id=route1 spring.cloud.gateway.routes.uri=http://httpbin.org:80 spring.cloud.gateway.routes.predicate[0]=Host=**.somehost.org spring.cloud.gateway.routes.predicate[1]=Path=/get spring.cloud.gateway.routes.filters[0]=Hystrix=hystrixCommandName ``` 限流:使用 RequestRateLimiter Gateway Filter 进行限流,示例代码: ``` spring.cloud.gateway.routes[0].id=count_route spring.cloud.gateway.routes[0].uri=http://httpbin.org:80 spring.cloud.gateway.routes[0].predicates[0]=Path=/get spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=my-limiter-key,2,10,PT1S ``` 降级:可以使用 Hystrix 进行降级,示例代码: ``` spring.cloud.gateway.routes[0].id=test_route spring.cloud.gateway.routes[0].uri=http://localhost:9090 spring.cloud.gateway.routes[0].predicates[0]=Path=/test spring.cloud.gateway.routes[0].filters[0]=Hystrix=mycommand ``` 3. Gateway 的集成 添加依赖 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ``` 4. 测试 启动服务后,访问 http://localhost:8080/get,可以看到服务正常返回。将请求频率配置为 0.1s,再次访问该 URL,可以看到服务返回 429 Too Many Requests。 参考资料: 1. Spring Cloud Hystrix 官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.2.1.RELEASE/reference/html/#spring-cloud-hystrix 2. Spring Cloud Gateway 官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值