SpringCloud入门(九):网关Gateway 之 熔断、降级(Greenwich.SR2)

简介

熔断降级:在分布式系统中,网关作为流量的入口,大量请求进入网关,向后端远系统或服务发起调通,后端服务不可避免的会产生调用失败(网络的波动等等…),失败时不能让所有请求堆积在网关,需要快速返回失败并返回,就需要在网关上做熔断降级。

代码实现

基于上一篇【SpringCloud入门(八):网关Gateway 之 服务注册与发现(Greenwich.SR2)】来继续。

熔断降级

pom引入依赖

 <!--熔断降级-->
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  </dependency>

yml

filters 下加入hystrix 配置

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      discovery:
        locator:
          #是否与服务发现组件结合,通过serviceId转发到具体的实例。默认为false,设为true开始根据serviceId创建路由功能
          enabled: false
          #是将请求路径上的服务名配置为小写(因为服务注册的时候,向注册中心注册时将服务名转成大写的了)
          lower-case-service-id: true
      routes:
        #自定义 全局唯一路由ID
        - id: feign-service
          #uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
          uri: lb://FEIGN-SERVICE
          #谓词
          predicates:
            #匹配路由   http://ip:port/feign/**  的请求
            - Path=/feign/**
          #过滤器
          filters:
            #剥离请求路径 例如 http://ip:port/feign/FEIGN-SERVICE/hello   ==>  http://ip:port/FEIGN-SERVICE/hello
            - StripPrefix=1
            #熔断降级
            - name: Hystrix
              args:
                name: feignHystrixCommand
                fallbackUri: 'forward:/fallbackCommand'

# hystrix
hystrix:
  command:
    #默认超时配置
    default:
      execution:
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 1000
    #指定服务超时配置
    feignHystrixCommand:
      execution:
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 5000

配置解读

  • name:必须为Hystrix
  • args
  1. name:即HystrixCommand的名字,可以针对不同的服务设置不同隔离类型、不同的超时时间
  2. fallbackUri:即 fallback 对应的 uri,这里的 uri 仅支持forward: schemed 的为参数
@RestController
public class HystrixCommandController {

    /**
     * @description 降级方法
     * @author hero良
     * @param
     * @exception
     * @version  1.0
     */
    @RequestMapping("/fallbackCommand")
    public Map<String,String> fallbackCommand(){
        Map<String,String> map = new HashMap<>();
        map.put("code","-1");
        map.put("message","服务异常");
        map.put("value","null");
        return map;
    }

这里我们设置的超时时间为5000,来修改feign服务的接口,使用sleep来设置阻塞6000

@GetMapping("/hello")
    public String hello(String name){
        log.info("      接收到请求       ");
        try {
            Thread.sleep(6000);
        }catch (InterruptedException e){
            log.error(e.getMessage(), e);
        }
        return "hello! " + name;
    }

进入我们的熔断方法。
在这里插入图片描述

发布了34 篇原创文章 · 获赞 5 · 访问量 1705

猜你喜欢

转载自blog.csdn.net/zhengliangs/article/details/103558897