Spring cloud gateway with resilience4j circuit breaker - ROM

Jiedao jdon 2021-05-04 12:36:01
spring cloud gateway resilience4j resilience

This article introduces how to use Spring Cloud The gateway will resilience4j The circuit breaker is used in combination with the back-end service behind the gateway , The method is as follows :

The whole code example is in github in .

Need to ask your Spring Cloud Gateway The application adds the following dependencies , Enabled Resilience4j Circuit breaker Integration :


Back end service routing configuration , As shown below :

    name: gateway-service
  output.ansi.enabled: ALWAYS
        - id: test-service-withResilient4j
          uri: http://localhost:8091
            - Path=/testService/**
            - RewritePath=/testService/(?<path>.*), /$\{path}

Now? ,Spring Cloud Circuit breaker starter Allow you to pass Customizer Use to configure Resilience4j Circuit breaker definition , This is the code first approach ( Customization through code is the default priority , Not through configuration customization ), But if you want to configure it from the outside , In this way, its configuration can be controlled from outside through distributed configuration service , So use Resilience4j spring boot starter Play a role , It makes the outside of the circuit breaker SpringBoot Configuration possible .

Resilience4j Of Spring Boot Starter Will be created based on your external configuration CircuitBreakerRegistery bean, Then you can inject it into Spring Cloud Starter Of resilience4j Factories for integration , this is it !

Resilience4j The external configuration of will be similar to :

      slidingWindowSize: 10
      minimumNumberOfCalls: 5
      permittedNumberOfCallsInHalfOpenState: 3
      automaticTransitionFromOpenToHalfOpenEnabled: true
      waitDurationInOpenState: 2s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10
        - org.springframework.web.client.HttpServerErrorException
        - java.io.IOException
        - java.lang.IllegalStateException
      slidingWindowSize: 100
      permittedNumberOfCallsInHalfOpenState: 30
      waitDurationInOpenState: 1s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10
        - java.lang.IllegalStateException
      baseConfig: default
      slidingWindowSize: 10
      minimumNumberOfCalls: 10
      permittedNumberOfCallsInHalfOpenState: 3
      waitDurationInOpenState: 1s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10

load Resilience4j The circuit breaker registry with Spring Cloud ReactiveResilience4JCircuitBreakerFactory The integration between them will be as follows :

public ReactiveResilience4JCircuitBreakerFactory reactiveResilience4JCircuitBreakerFactory(CircuitBreakerRegistry circuitBreakerRegistry) {
    ReactiveResilience4JCircuitBreakerFactory reactiveResilience4JCircuitBreakerFactory = new ReactiveResilience4JCircuitBreakerFactory();
    return reactiveResilience4JCircuitBreakerFactory;

Now is the time to test the integration and see how it works :

  • We will use the simulation server test container to simulate the target back-end services provided through the gateway
  • We will stub some responses
  • Then trigger the test and monitor the log , To understand ciruitbreaker Reaction and deviation from the route , You can Resilience4j Supported metrics expose and events capture a large number of metrics

Add the following dependencies to enable emulation Mock Use of servers :


Now? , You need to configure the test container starup, And inject the custom configuration of routing after the simulation server starts :

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ContextConfiguration(initializers = {GatewayCircuitBreakerTest.Initializer.class})
public class GatewayCircuitBreakerTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(GatewayCircuitBreakerTest.class);
    private static MockServerContainer mockServerContainer;
    static {
        mockServerContainer = new MockServerContainer();
    static class Initializer
            implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
                    "spring.cloud.gateway.routes[0].uri=" + mockServerContainer.getEndpoint(),
                    "spring.cloud.gateway.routes[0].predicates[0]=" + "Path=/testService/**",
                    "spring.cloud.gateway.routes[0].filters[0]=" + "RewritePath=/testService/(?<path>.*), /$\\{path}",
                    "spring.cloud.gateway.routes[0].filters[1].name=" + "CircuitBreaker",
                    "spring.cloud.gateway.routes[0].filters[1].args.name=" + "backendA",
                    "spring.cloud.gateway.routes[0].filters[1].args.fallbackUri=" + "forward:/fallback/testService"
    private MockServerClient client = new MockServerClient(mockServerContainer.getContainerIpAddress(), mockServerContainer.getServerPort());
    private TestRestTemplate template;
    public static void close(){

Last , You can use the class GatewayCircuitBreakerTest in Trigger the test of the protected endpoint , And by analyzing the events reported in the console to see that it is passing Resilience4j Circuit breaker .


本文为[Jiedao jdon]所创,转载请带上原文链接,感谢

  1. Microservice mode: business process saga mode of spring boot + Kafka - vinsguru
  2. Linux / MacOS 修改 ls 显示年月日的时间格式
  3. Linux / MacOS modify the time format of LS display date
  4. 7、Spring Boot检索
  5. 7. Spring boot search
  6. 7、Spring Boot检索
  7. 7. Spring boot search
  8. 10、Spring Boot分布式
  9. 10. Spring boot distributed
  10. Did you know that artifact can also manage SUSE Linux system dependencies
  11. 3、Spring Cloud Rest工程建立(通過IDEA建立)
  12. 3. Spring cloud rest project establishment (through idea)
  13. 4、Spring Cloud Eureka
  14. 4、Spring Cloud Eureka
  15. Did you know that artifact can also manage SUSE Linux system dependencies
  16. k8s搭建zk&pulsar集群——三节点
  17. 7、Spring Cloud Hystrix
  18. Dubbo series -- source code analysis of local service publishing
  19. Netty启动对HTTP/3的孵化器支持
  20. Netty launches incubator support for HTTP / 3
  21. Spring Webflux security configuration tutorial and source code - vinsguru
  22. WebClient: Spring的新的HTTP反应式客户端 - spring.io
  23. Webclient: spring's new HTTP reactive client- spring.io
  24. 使用Project Reactor进行反应式数据流 - spring.io
  25. Using project reactor for reactive data flow- spring.io
  26. Humor: k8s is not so hard to deploy on kubernetes personal blog
  27. UNIX domain socket tutorial for java16 - nipafx
  28. Using netty to realize the source code and tutorial of http2 server / client baeldung
  29. Using spring boot reactive r2dbc to realize crud operation source code of PostgreSQL Rajesh
  30. Spring Boot Liquibase基础教程 - josdem
  31. Vlad mihalcea: the best way to map query results to dto using JPA and Hibernate
  32. Using java enumeration in spring boot to automatically serialize parameters and save database - Dario
  33. In depth study of spring cloud load balancer - Piotr
  34. How to use completable future in springboot 2
  35. Basic course of spring boot liquibase - josdem
  36. Volatile side effect in Java: not using CPU cache
  37. Using redis PubSub and spring boot to realize microservice message model vinsguru
  38. Fault tolerant and reliable messaging of Apache Kafka and spring boot – Arnold galovics
  39. Java exception and tuning one stop solution
  40. Using playwright to implement automatic visual testing for Java API - applitools
  41. Oracle database official statement does not support VMWare
  42. [function] Oracle function series (1) -- character function
  43. [function] Oracle function series (1) -- character function
  44. Oracle character set simple diagram, Chinese garbled solution
  45. Oracle lock series
  46. No.2 process kthread of Linux kernel learning
  47. [password] Oracle user password series
  48. [Linux] migrate Oracle installation directory from root directory to logical volume
  49. Oracle 12cr1 RAC installation on VMware Workstation (middle) - graphical interface installation
  50. Driving of Oracle hint_ SITE
  51. Oracle 12cr1 RAC installation on VMware Workstation (middle) - graphical interface installation
  52. [knowledge point sorting] comparison of redo, undo and execution speed under nologing, append, archive and parallel in Oracle
  53. Introduction to Oracle parameters
  54. [method] how to limit IP access to Oracle database
  55. Oracle 12cr1 RAC installation on VMware Workstation (middle) - graphical interface installation
  56. Linux free - M command
  57. Oracle fast recovery area (FRA)
  58. Docker install MySQL 5.7
  59. Oracle 12C EM Express Series
  60. [DG] Oracle 19C uses DBCA to build physical DG