Spring cloud gateway integrates sentinel to realize gateway current restriction

Time:2020-3-31

This article mainly introduces the integration of spring cloud gateway and sentinel to realize gateway current restriction. The example code is introduced in detail in this article, which has certain reference value for your study or work. You can refer to the following for your friends

Note: sentinel can be used as the current limiting component of each microservice or gateway gateway. Spring cloud gateway has limited flow function, but sentinel is used as a substitute here.

Note: sentinel flow control can be placed on gateway gateway gateway or microserver.

1. Create a child project based on the parent project

2. Add POM dependency


<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

2. Add configuration item


server:
 port: 9092
spring:
 cloud:
  nacos:
   discovery:
    register-enabled: false
    server-addr: localhost:8848
    namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
  sentinel:
   transport:
    dashboard: localhost:8080
    port: 8719
   scg:
    fallback:
     mode: response
     response-status: 455
     response-body: error!
  gateway:
   routes:
    - id: demo_route
     uri: lb://demo
     predicates:
      - Path=/demo/**
    - id: demo2_test
     uri: lb://demo2
     predicates:
      - Path=/user/**
 application:
  name: gateway-sentinel

Scg.fallback is the response configuration after sentinel current limiting

3. Startup class


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

4. After startup, gateway sentinel application can be seen in sentinel console, and flow control rules can be set through console.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.