SpringCloudAlibaba-17-sentinel整合gateway限流

前言

本节主要讲解sentinel整合gateway网关


sentinel支持以下两种模式的限流

内容

实践

1.创建网关
  1. 1.创建一个非web依赖的工程:sentinel-gateway
  2. 2.作为一个网关,需要使用sentinel限流,并且注册到nacos上,需要引入出基本的spring cloud组件后,需要再次引入:sentinel依赖,服务发现依赖,网关依赖,网关和sentinel结合依赖。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!--gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--服务发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--sentinel和gateway整合-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
  1. 3.配置文件定义
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
server:
port: 18084
spring:
application:
name: sentinel-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: 127.0.0.1:8080
#配置降级策略
scg:
fallback:
mode: response
response-status: 426
response-body: error request
#gateway路由规则
gateway:
routes:
- id: test_route
uri: lb://sentinel-gateway-service
predicates:
- Path=/test/**
  1. 4.启动类添加注解:@SpringCloudApplication
2.创建网关下游的服务
  1. 1.创建一个非web依赖的工程:sentinel-gateway-service
  2. 2.作为一个网关下测试服务,需要注册到nacos上。
1
2
3
4
5
<!--服务发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  1. 3.配置文件定义
1
2
3
4
5
6
7
8
9
spring:
application:
name: sentinel-gateway-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
server:
port: 18086
  1. 4.启动类添加注解:@EnableDiscoveryClient、@SpringBootApplication

  2. 5.创建测试类:

1
2
3
4
5
6
7
8
9
10
11
@RestController
public class DemoController {
/**
* 因为在gateway中路由规则,都是test的会被拦截
* @return
*/
@GetMapping("/test")
public String test(){
return "test";
}
}
3.访问网关路由到对应的下游服务

访问网关:http://localhost:18084/test
返回:test

4.结合sentinel进行降级
  1. 1.第一种限流规则:针对route

http://127.0.0.1:8080/进入登录sentinel
然后”流控规则”

再次访问:
http://localhost:18084/test
返回:
error request

  1. 2.第二种限流规则:API分组限流
    a.先创建api分组
    Sentinel 控制台–>API管理–>新建API分组

再次访问:
http://localhost:18084/test
返回:
error request

毕业于<br>相信技术可以改变人与人之间的生活<br>码农一枚