spring cloud gateway集成hystrix全局断路器操作

gateway集成hystrix全局断路器

pom.xml添加依赖

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>

在配置文件中,增加spring.cloud.gateway.default-filters:

default-filters:- name: Hystrix  args:    name: fallbackcmd    fallbackUri: forward:/fallbackcontroller

一定要注意是spring.cloud.gateway.default-filters这个配置节。

如上的配置,将会使用HystrixCommand打包剩余的过滤器,并命名为fallbackcmd,我们还配置了可选的参数fallbackUri,降级逻辑被调用,请求将会被转发到URI为/fallbackcontroller的控制器处理。

定义降级处理如下:

@RequestMapping(value = "/fallbackcontroller")public Map<String, String> fallBackController() {    Map<String, String> res = new HashMap();    res.put("code", "-100");    res.put("data", "service not available");    return res;}

此时可以设置hystrix超时时间(毫秒) ,默认只有2秒

hystrix:  command:    default:      execution:        isolation:          thread:            timeoutInMilliseconds: 30000

示例代码:

https://github.com/wanghongqi/springcloudconsul_test/tree/master/springtest_gateway

spring cloud gateway 全局熔断

熔断主要保护的是调用方服务,如某A服务调用B服务的rpc接口,突然B服务接口不稳定,表现为接口延迟或者失败率变大。

这个时候如果对B服务调用不能快速失败,那么会导致A服务大量线程资源无法释放导致最终A服务不稳定,故障点由B服务传递到A服务,故障扩大。

熔断就是在B服务出现故障的情况下,断开对B的调用,通过快速失败来保证A服务的稳定。

一:Gateway项目maven引入依赖包

Spring Cloud Gateway 利用 Hystrix 的熔断特性,在流量过大时进行服务降级,同样我们还是首先给项目添加上依赖

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId></dependency>

二:创建熔断后转发的请求

@RestControllerpublic class FallbackController {    private Logger log= LoggerFactory.getLogger(getClass());    @RequestMapping("/error/fallback")    public Object fallacak(){        log.info("熔断处理!!!");        return "Service Error!!!";    }}

三:yml配置

#全局熔断拦截器default-filters:    - name: Hystrix      args:        name: fallbackcmd        fallbackUri: forward:/error/fallback    - name: Retry      args:        retries: 3        statuses: BAD_GATEWAY,BAD_REQUEST        methods: GET,POST

Hystrix是Gateway以封装好的过滤器。如果不了解请查看:GatwayFilter工厂

name:即HystrixCommand的名字

fallbackUri:forward:/error/fallback 配置了 fallback 时要会调的路径,当调用 Hystrix 的 fallback 被调用时,请求将转发到/error/fallback 这个 URI

Retry 通过这四个参数来控制重试机制: retries, statuses, methods, 和 series

retries:重试次数,默认值是 3 次

statuses:HTTP 的状态返回码,取值请参考:org.springframework.http.HttpStatus

methods:指定哪些方法的请求需要进行重试逻辑,默认值是 GET 方法,取值参考:org.springframework.http.HttpMethod

series:一些列的状态码配置,取值参考:org.springframework.http.HttpStatus.Series。符合的某段状态码才会进行重试逻辑,默认值是 SERVER_ERROR,值是 5,也就是 5XX(5 开头的状态码),共有5 个值。

# hystrix 信号量隔离,3秒后自动超时hystrix:    command:        fallbackcmd:            execution:                isolation:                    strategy: SEMAPHORE                    thread:                        timeoutInMilliseconds: 3000

fallbackcmd 此处需要和上面设置的HystrixCommand一致

timeoutInMilliseconds 设置超时时间

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

人生就像一场旅行,不必在乎目的地,

spring cloud gateway集成hystrix全局断路器操作

相关文章:

你感兴趣的文章:

标签云: