服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 深入学习spring cloud gateway 限流熔断

深入学习spring cloud gateway 限流熔断

2021-09-10 12:09coding途中 Java教程

这篇文章主要介绍了深入学习spring cloud gateway 限流熔断,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

目前,spring cloud gateway是仅次于spring cloud netflix的第二个最受欢迎的spring cloud项目(就github上的星级而言)。它是作为spring cloud系列中zuul代理的继任者而创建的。该项目提供了用于微服务体系结构的api网关,并基于反应式netty和project reactor构建。它旨在提供一种简单而有效的方法来路由到api并解决诸如安全性,监视/度量和弹性之类的普遍关注的问题。

基于redis限流

spring cloud gateway为您提供了许多功能和配置选项。今天,我将集中讨论网关配置的一个非常有趣的方面-速率限制。速率限制器可以定义为一种控制网络上发送或接收的流量速率的方法。我们还可以定义几种类型的速率限制。spring cloud gateway当前提供了一个request rate limiter,它负责将每个用户每秒限制为n个请求。与spring cloud gateway一起 使用时requestratelimiter,我们可能会利用redis。spring cloud实现使用令牌桶算法做限速。该算法具有集中式存储桶主机,您可以在其中对每个请求获取令牌,然后将更多的令牌缓慢滴入存储桶中。如果存储桶为空,则拒绝该请求。

项目演示源码地址:https://github.com/1ssqq1lxr/springcloudgatewaytest

引入maven依赖

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
## spring cloud依赖
<parent>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-parent</artifactid>
   <version>2.2.1.release</version>
</parent>
 
<properties>
   <project.build.sourceencoding>utf-8</project.build.sourceencoding>
   <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
   <java.version>11</java.version>
   <spring-cloud.version>hoxton.rc2</spring-cloud.version>
</properties>
 
<dependencymanagement>
   <dependencies>
      <dependency>
         <groupid>org.springframework.cloud</groupid>
         <artifactid>spring-cloud-dependencies</artifactid>
         <version>${spring-cloud.version}</version>
         <type>pom</type>
         <scope>import</scope>
      </dependency>
   </dependencies>
</dependencymanagement>
 
## gateway 依赖
<dependency>
   <groupid>org.springframework.cloud</groupid>
   <artifactid>spring-cloud-starter-gateway</artifactid>
</dependency>
<dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-data-redis-reactive</artifactid>
</dependency>
<dependency>
   <groupid>org.projectlombok</groupid>
   <artifactid>lombok</artifactid>
</dependency>
<dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-test</artifactid>
   <scope>test</scope>
</dependency>
<dependency>
   <groupid>org.testcontainers</groupid>
   <artifactid>mockserver</artifactid>
   <version>1.12.3</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupid>org.mock-server</groupid>
   <artifactid>mockserver-client-java</artifactid>
   <version>3.10.8</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupid>com.carrotsearch</groupid>
   <artifactid>junit-benchmarks</artifactid>
   <version>0.7.2</version>
   <scope>test</scope>
</dependency>

限流器配置

使用spring cloud gateway默认请求限流gatewayfilter(org.springframework.cloud.gateway.filter.ratelimit.redisratelimiter)。使用默认的redis限流器方案,你可以通过自定义keyresolver类去决定redis限流key的生成,下面举常用几个例子:

根据用户: 使用这种方式限流,请求路径中必须携带userid参数

?
1
2
3
4
@bean
keyresolver userkeyresolver() {
 return exchange -> mono.just(exchange.getrequest().getqueryparams().getfirst("userid"));
}

根据获uri

?
1
2
3
4
@bean
keyresolver apikeyresolver() {
 return exchange -> mono.just(exchange.getrequest().getpath().value());
}

由于我们已经讨论了spring cloud gateway速率限制的一些理论方面,因此我们可以继续进行实施。首先,让我们定义主类和非常简单的keyresolverbean,它始终等于一个。

?
1
2
3
4
5
6
7
8
9
10
11
12
@springbootapplication
public class gatewayapplication {
 
   public static void main(string[] args) {
      springapplication.run(gatewayapplication.class, args);
   }
 
   @bean
   keyresolver userkeyresolver() {
      return exchange -> mono.just("1");
   }
}

gateway默认使用org.springframework.cloud.gateway.filter.ratelimit.redisratelimiter限流器。 现在,如通过模拟http请求,则会收到以下响应。它包括一些特定的header,其前缀为x-ratelimit。

  • x-ratelimit-burst-capacity:最大令牌值,
  • x-ratelimit-replenish-rate:填充的速率值,
  • x-ratelimit-remaining:剩下可请求数。

yaml配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
  port: ${port:8085}
 
spring:
  application:
    name: gateway-service
  redis:
    host: localhost
    port: 6379
  cloud:
    gateway:
      routes:
      - id: account-service
        uri: http://localhost:8091
        predicates:
        - path=/account/**
        filters:
        - rewritepath=/account/(?.*), /$\{path}
      - name: requestratelimiter
          args:
            redis-rate-limiter.replenishrate: 10
            redis-rate-limiter.burstcapacity: 20

redis限流器实现

关键源码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// routeid也就是我们的服务路由id,id就是限流的key
public mono<response> isallowed(string routeid, string id) {
 // 会判断redisratelimiter是否初始化了
 if (!this.initialized.get()) {
  throw new illegalstateexception("redisratelimiter is not initialized");
 }
 // 获取routeid对应的限流配置
 config routeconfig = getconfig().getordefault(routeid, defaultconfig);
 
 if (routeconfig == null) {
  throw new illegalargumentexception("no configuration found for route " + routeid);
 }
 
 // 允许用户每秒做多少次请求
 int replenishrate = routeconfig.getreplenishrate();
 
 // 令牌桶的容量,允许在一秒钟内完成的最大请求数
 int burstcapacity = routeconfig.getburstcapacity();
 
 try {
  // 限流key的名称(request_rate_limiter.{localhost}.timestamp,request_rate_limiter.{localhost}.tokens)
  list<string> keys = getkeys(id);
 
 
  // the arguments to the lua script. time() returns unixtime in seconds.
  list<string> scriptargs = arrays.aslist(replenishrate + "", burstcapacity + "",
    instant.now().getepochsecond() + "", "1");
  // allowed, tokens_left = redis.eval(script, keys, args)
  // 执行lua脚本
  flux<list<long>> flux = this.redistemplate.execute(this.script, keys, scriptargs);
    // .log("redisratelimiter", level.finer);
  return flux.onerrorresume(throwable -> flux.just(arrays.aslist(1l, -1l)))
    .reduce(new arraylist<long>(), (longs, l) -> {
     longs.addall(l);
     return longs;
    }) .map(results -> {
     boolean allowed = results.get(0) == 1l;
     long tokensleft = results.get(1);
 
     response response = new response(allowed, getheaders(routeconfig, tokensleft));
 
     if (log.isdebugenabled()) {
      log.debug("response: " + response);
     }
     return response;
    });
 }
 catch (exception e) {
  log.error("error determining if user allowed from redis", e);
 }
 return mono.just(new response(true, getheaders(routeconfig, -1l)));
}

测试redis限流器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@springboottest(webenvironment = springboottest.webenvironment.defined_port)
@runwith(springrunner.class)
public class gatewayratelimitertest {
 
    private static final logger logger = loggerfactory.getlogger(gatewayratelimitertest.class);
 
    @rule
    public testrule benchmarkrun = new benchmarkrule();
 
    @classrule
    public static mockservercontainer mockserver = new mockservercontainer();
    @classrule
    public static genericcontainer redis = new genericcontainer("redis:5.0.6").withexposedports(6379);
 
    @autowired
    testresttemplate template;
 
    @beforeclass
    public static void init() {
 
        system.setproperty("spring.cloud.gateway.routes[0].id", "account-service");
        system.setproperty("spring.cloud.gateway.routes[0].uri", "http://localhost:" + mockserver.getserverport());
        system.setproperty("spring.cloud.gateway.routes[0].predicates[0]", "path=/account/**");
        system.setproperty("spring.cloud.gateway.routes[0].filters[0]", "rewritepath=/account/(?<path>.*), /$\\{path}");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].name", "requestratelimiter");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.redis-rate-limiter.replenishrate", "10");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.redis-rate-limiter.burstcapacity", "20");
        system.setproperty("spring.redis.host", "localhost");
        system.setproperty("spring.redis.port", "" + redis.getmappedport(6379));
        new mockserverclient(mockserver.getcontaineripaddress(), mockserver.getserverport())
                .when(httprequest.request()
                        .withpath("/1"))
                .respond(response()
                        .withbody("{\"id\":1,\"number\":\"1234567890\"}")
                        .withheader("content-type", "application/json"));
    }
 
    @test
    @benchmarkoptions(warmuprounds = 0, concurrency = 6, benchmarkrounds = 600)
    public void testaccountservice() {
        responseentity<account> r = template.exchange("/account/{id}", httpmethod.get, null, account.class, 1);
        logger.info("received: status->{}, payload->{}, remaining->{}", r.getstatuscodevalue(), r.getbody(), r.getheaders().get("x-ratelimit-remaining"));
//  assert.assertequals(200, r.getstatuscodevalue());
//  assert.assertnotnull(r.getbody());
//  assert.assertequals(integer.valueof(1), r.getbody().getid());
//  assert.assertequals("1234567890", r.getbody().getnumber());
    }
}

执行test类: 发现超过20之后会被拦截返回429,运行过程中随着令牌的放入会不断有请求成功。

14:20:32.242 --- [pool-2-thread-1] : received: status->200, payload->account(id=1, number=1234567890), remaining->[18]
14:20:32.242 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[16]
14:20:32.242 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[14]
14:20:32.242 --- [pool-2-thread-3] : received: status->200, payload->account(id=1, number=1234567890), remaining->[15]
14:20:32.242 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[17]
14:20:32.242 --- [pool-2-thread-5] : received: status->200, payload->account(id=1, number=1234567890), remaining->[19]
14:20:32.294 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[15]
14:20:32.297 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[19]
14:20:32.304 --- [pool-2-thread-3] : received: status->200, payload->account(id=1, number=1234567890), remaining->[18]
14:20:32.308 --- [pool-2-thread-5] : received: status->200, payload->account(id=1, number=1234567890), remaining->[16]
14:20:32.309 --- [pool-2-thread-1] : received: status->200, payload->account(id=1, number=1234567890), remaining->[17]
14:20:32.312 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[14]
14:20:32.320 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[13]
14:20:32.326 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[12]
14:20:32.356 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[7]
14:20:32.356 --- [pool-2-thread-5] : received: status->200, payload->account(id=1, number=1234567890), remaining->[10]
14:20:32.361 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[6]
14:20:32.363 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[8]
14:20:32.384 --- [pool-2-thread-5] : received: status->200, payload->account(id=1, number=1234567890), remaining->[4]
14:20:32.384 --- [pool-2-thread-3] : received: status->200, payload->account(id=1, number=1234567890), remaining->[11]
14:20:32.386 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[5]
14:20:32.390 --- [pool-2-thread-1] : received: status->200, payload->account(id=1, number=1234567890), remaining->[9]
14:20:32.391 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[3]
14:20:32.392 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[2]
14:20:32.403 --- [pool-2-thread-6] : received: status->429, payload->null, remaining->[0]
14:20:32.403 --- [pool-2-thread-4] : received: status->429, payload->null, remaining->[0]
........
14:20:33.029 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[9]
14:20:33.033 --- [pool-2-thread-1] : received: status->200, payload->account(id=1, number=1234567890), remaining->[8]
14:20:33.033 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[7]
14:20:33.037 --- [pool-2-thread-3] : received: status->200, payload->account(id=1, number=1234567890), remaining->[6]
14:20:33.039 --- [pool-2-thread-5] : received: status->200, payload->account(id=1, number=1234567890), remaining->[5]
14:20:33.046 --- [pool-2-thread-6] : received: status->200, payload->account(id=1, number=1234567890), remaining->[4]
14:20:33.052 --- [pool-2-thread-5] : received: status->429, payload->null, remaining->[0]
14:20:33.058 --- [pool-2-thread-6] : received: status->429, payload->null, remaining->[0]
14:20:33.058 --- [pool-2-thread-1] : received: status->200, payload->account(id=1, number=1234567890), remaining->[2]
14:20:33.060 --- [pool-2-thread-5] : received: status->429, payload->null, remaining->[0]
14:20:33.081 --- [pool-2-thread-4] : received: status->200, payload->account(id=1, number=1234567890), remaining->[1]
14:20:33.082 --- [pool-2-thread-3] : received: status->200, payload->account(id=1, number=1234567890), remaining->[0]
14:20:33.084 --- [pool-2-thread-2] : received: status->200, payload->account(id=1, number=1234567890), remaining->[3]
14:20:33.088 --- [pool-2-thread-5] : received: status->429, payload->null, remaining->[0]
如果默认的限流器不能够满足使用,可以通过继承abstractratelimiter实现自定义限流器,然后通过routelocator方式去注入拦截器。

resilience4j熔断器

引入依赖

?
1
2
3
4
5
6
7
8
<dependency>
   <groupid>org.springframework.cloud</groupid>
   <artifactid>spring-cloud-starter-gateway</artifactid>
</dependency>
<dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactid>
</dependency>

resilience4j 断路器介绍

三个一般性状态

  • closed:关闭状态,放过所有请求,记录请求状态。
  • open:打开,异常请求达到阀值数量时,开启熔断,拒绝所有请求。
  • half_open:半开,放开一定数量的请求,重新计算错误率。

两个特定状态

  • disabled:禁用
  • forced_open:强开

状态之间转换

启动时断路器为close状态,在达到一定请求量至后计算请求失败率,达到或高于指定失败率后,断路进入open状态,阻拦所有请求,开启一段时间(自定义)时间后,断路器变为halfopen状态,重新计算请求失败率。halfopen错误率低于指定失败率后,断路进入close状态,否则进入open状态。

深入学习spring cloud gateway 限流熔断

状态转换

通过resilience4j启用spring cloud gateway断路器

要启用构建在resilience4j之上的断路器,我们需要声明一个customizer传递了的bean reactiveresilience4jcircuitbreakerfactory。可以非常简单地去配置设置,下面使用默认配置进行测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@bean
public customizer<reactiveresilience4jcircuitbreakerfactory> defaultcustomizer() {
   return factory -> factory.configuredefault(id -> new resilience4jconfigbuilder(id)
      .circuitbreakerconfig(circuitbreakerconfig.custom()
          //统计失败率的请求总数
         .slidingwindowsize(5)
         //在半开状态下请求的次数
         .permittednumberofcallsinhalfopenstate(5)
         //断路器打开的成功率
         .failureratethreshold(50.0f)
         //断路器打开的周期
         .waitdurationinopenstate(duration.ofmillis(30))
         //属于慢请求的周期
         .slowcalldurationthreshold(duration.ofmillis(200))
        //慢请求打开断路器的成功率
         .slowcallratethreshold(50.0f)
         .build())
      .timelimiterconfig(timelimiterconfig.custom().timeoutduration(duration.ofmillis(200)).build()).build());
}

测试resilience4j断路器

使用默认配置进行测试

?
1
2
3
4
5
6
7
8
9
10
@bean
public customizer<reactiveresilience4jcircuitbreakerfactory> defaultcustomizer() {
    return factory -> factory.configuredefault(id -> new resilience4jconfigbuilder(id)
.circuitbreakerconfig(circuitbreakerconfig.ofdefaults())
            .circuitbreakerconfig(circuitbreakerconfig.custom()
                    .slowcalldurationthreshold(duration.ofmillis(200))
                    .build())
            .timelimiterconfig(timelimiterconfig.custom().timeoutduration(duration.ofmillis(200)).build())
            .build());
}

执行下面test用例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@springboottest(webenvironment = springboottest.webenvironment.defined_port)
@runwith(springrunner.class)
public class gatewaycircuitbreakertest {
 
 
    private static final logger logger = loggerfactory.getlogger(gatewayratelimitertest.class);
 
    @rule
    public testrule benchmarkrun = new benchmarkrule();
 
    @classrule
    public static mockservercontainer mockserver = new mockservercontainer();
 
    @autowired
    testresttemplate template;
    final random random = new random();
    int i = 0;
 
    @beforeclass
    public static void init() {
        system.setproperty("logging.level.org.springframework.cloud.gateway.filter.factory", "trace");
        system.setproperty("spring.cloud.gateway.routes[0].id", "account-service");
        system.setproperty("spring.cloud.gateway.routes[0].uri", "http://localhost:" + mockserver.getserverport());
        system.setproperty("spring.cloud.gateway.routes[0].predicates[0]", "path=/account/**");
        system.setproperty("spring.cloud.gateway.routes[0].filters[0]", "rewritepath=/account/(?<path>.*), /$\\{path}");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].name", "circuitbreaker");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.name", "exampleslowcircuitbreaker");
//        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.slowcalldurationthreshold", "100");
//        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.slowcallratethreshold", "9.0f");
//        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.fallbackuri", "forward:/fallback/account");
        mockserverclient client = new mockserverclient(mockserver.getcontaineripaddress(), mockserver.getserverport());
        client.when(httprequest.request()
                .withpath("/1"))
                .respond(response()
                        .withbody("{\"id\":1,\"number\":\"1234567890\"}")
                        .withheader("content-type", "application/json"));
//        client.when(httprequest.request()
//                .withpath("/2"), times.exactly(3))
//    .respond(response()
//                        .withbody("{\"id\":2,\"number\":\"1\"}")
//                        .withdelay(timeunit.seconds, 1000)
//                        .withheader("content-type", "application/json"));
        client.when(httprequest.request()
                .withpath("/2"))
                .respond(response()
                        .withbody("{\"id\":2,\"number\":\"1234567891\"}")
                        .withdelay(timeunit.seconds, 200)
                        .withheader("content-type", "application/json"));
    }
 
    @test
    @benchmarkoptions(warmuprounds = 0, concurrency = 1, benchmarkrounds = 600)
    public void testaccountservice() {
        int gen = 1 + (i++ % 2);
        responseentity<account> r = template.exchange("/account/{id}", httpmethod.get, null, account.class, gen);
        logger.info("{}. received: status->{}, payload->{}, call->{}", i, r.getstatuscodevalue(), r.getbody(), gen);
    }
}

请求日志如下:当请求达到100次时候,此时失败率为50% 这时候系统开启断路器返回503!

20:07:29.281 --- [pool-2-thread-1] : 91. received: status->200, payload->account(id=1, number=1234567890), call->1
20:07:30.297 --- [pool-2-thread-1] : 92. received: status->504, payload->account(id=null, number=null), call->2
20:07:30.316 --- [pool-2-thread-1] : 93. received: status->200, payload->account(id=1, number=1234567890), call->1
20:07:31.328 --- [pool-2-thread-1] : 94. received: status->504, payload->account(id=null, number=null), call->2
20:07:31.345 --- [pool-2-thread-1] : 95. received: status->200, payload->account(id=1, number=1234567890), call->1
20:07:32.359 --- [pool-2-thread-1] : 96. received: status->504, payload->account(id=null, number=null), call->2
20:07:32.385 --- [pool-2-thread-1] : 97. received: status->200, payload->account(id=1, number=1234567890), call->1
20:07:33.400 --- [pool-2-thread-1] : 98. received: status->504, payload->account(id=null, number=null), call->2
20:07:33.414 --- [pool-2-thread-1] : 99. received: status->200, payload->account(id=1, number=1234567890), call->1
20:07:34.509 --- [pool-2-thread-1] : 100. received: status->504, payload->account(id=null, number=null), call->2
20:07:34.525 --- [pool-2-thread-1] : 101. received: status->503, payload->account(id=null, number=null), call->1
20:07:34.533 --- [pool-2-thread-1] : 102. received: status->503, payload->account(id=null, number=null), call->2
20:07:34.539 --- [pool-2-thread-1] : 103. received: status->503, payload->account(id=null, number=null), call->1
20:07:34.545 --- [pool-2-thread-1] : 104. received: status->503, payload->account(id=null, number=null), call->2
20:07:34.552 --- [pool-2-thread-1] : 105. received: status->503, payload->account(id=null, number=null), call->1
20:07:34.566 --- [pool-2-thread-1] : 106. received: status->503, payload->account(id=null, number=null), call->2
20:07:34.572 --- [pool-2-thread-1] : 107. received: status->503, payload->account(id=null, number=null), call->1
20:07:34.576 --- [pool-2-thread-1] : 108. received: status->503, payload->account(id=null, number=null), call->2
20:07:34.580 --- [pool-2-thread-1] : 109. received: status->503, payload->account(id=null, number=null), call->1
20:07:34.586 --- [pool-2-thread-1] : 110. received: status->503, payload->account(id=null, number=null), call->2
20:07:34.591 --- [pool-2-thread-1] : 111. received: status->503, payload->account(id=null, number=null), call->1

这时候我们修改下配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
     @beforeclass
    public static void init() {
        system.setproperty("logging.level.org.springframework.cloud.gateway.filter.factory", "trace");
        system.setproperty("spring.cloud.gateway.routes[0].id", "account-service");
        system.setproperty("spring.cloud.gateway.routes[0].uri", "http://localhost:" + mockserver.getserverport());
        system.setproperty("spring.cloud.gateway.routes[0].predicates[0]", "path=/account/**");
        system.setproperty("spring.cloud.gateway.routes[0].filters[0]", "rewritepath=/account/(?<path>.*), /$\\{path}");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].name", "circuitbreaker");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.name", "exampleslowcircuitbreaker");
//        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.slowcalldurationthreshold", "100");
//        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.slowcallratethreshold", "9.0f");
        system.setproperty("spring.cloud.gateway.routes[0].filters[1].args.fallbackuri", "forward:/fallback/account");
        mockserverclient client = new mockserverclient(mockserver.getcontaineripaddress(), mockserver.getserverport());
        client.when(httprequest.request()
                .withpath("/1"))
                .respond(response()
                        .withbody("{\"id\":1,\"number\":\"1234567890\"}")
                        .withheader("content-type", "application/json"));
        client.when(httprequest.request()
                .withpath("/2"), times.exactly(3))
    .respond(response()
                        .withbody("{\"id\":2,\"number\":\"1\"}")
                        .withdelay(timeunit.seconds, 1000)
                        .withheader("content-type", "application/json"));
        client.when(httprequest.request()
                .withpath("/2"))
                .respond(response()
                        .withbody("{\"id\":2,\"number\":\"1234567891\"}")
//                        .withdelay(timeunit.seconds, 200)
                        .withheader("content-type", "application/json"));
    }

新建一个回调接口,用于断路器打开后请求的地址。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@restcontroller
@requestmapping("/fallback")
public class gatewayfallback {
 
    @getmapping("/account")
    public account getaccount() {
        account a = new account();
        a.setid(2);
        a.setnumber("123456");
        return a;
    }
 
}

使用默认设置时,前3次请求触发断路器回调,后面正常请求成功

20:20:23.529 --- [pool-2-thread-1] : 1. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:23.777 --- [pool-2-thread-1] : 2. received: status->200, payload->account(id=2, number=123456), call->2
20:20:23.808 --- [pool-2-thread-1] : 3. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:24.018 --- [pool-2-thread-1] : 4. received: status->200, payload->account(id=2, number=123456), call->2
20:20:24.052 --- [pool-2-thread-1] : 5. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:24.268 --- [pool-2-thread-1] : 6. received: status->200, payload->account(id=2, number=123456), call->2
20:20:24.301 --- [pool-2-thread-1] : 7. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:24.317 --- [pool-2-thread-1] : 8. received: status->200, payload->account(id=2, number=1234567891), call->2
20:20:24.346 --- [pool-2-thread-1] : 9. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:24.363 --- [pool-2-thread-1] : 10. received: status->200, payload->account(id=2, number=1234567891), call->2
20:20:24.378 --- [pool-2-thread-1] : 11. received: status->200, payload->account(id=1, number=1234567890), call->1
20:20:24.392 --- [pool-2-thread-1] : 12. received: status->200, payload->account(id=2, number=1234567891), call->2
20:20:24.402 --- [pool-2-thread-1] : 13. received: status->200, payload->account(id=1, number=1234567890), call->1

至此给大家介绍了spring cloud gateway中断路器跟限流器使用。更多相关spring cloud gateway 限流熔断内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/1ssqq1lxr/p/14680663.html

延伸 · 阅读

精彩推荐