Java之SpringCloud Alibaba【八】【Spring Cloud微服务Gateway整合sentinel限流】

一、Gateway整合sentinel限流

网关作为内部系统外的一层屏障,对内起到-定的保护作用,限流便是其中之- - .网关层的限流可以简单地针对不同路由进行限流,也可针对业务的接口进行限流,或者根据接口的特征分组限流。

1、添加依赖

xml 复制代码
<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-sentinel</artifactId>
</dependency>

2、添加配置

yml 复制代码
server:
  port: 8088
spring:
  application:
    name: api-gateway
# gateway的配置
  cloud:
    gateway:
      routes:
        - id: order_route #路由的唯一标识,路由到order
          uri: lb://order-service # 需要转发的地址  lb指的是从nacos中按照名称获取微服务,并遵循负载均衡策略 order-service服务名
          #断言规则 用于路由规则的匹配
          predicates:
            - Path=/order/**
              # http://localhost:8088/order-serve/order/add  路由到↓
              # http://localhost:8020/order-serve/order/add
            #- After=2020-10-19T09:07:00.660+08:00[Asia/Shanghai]
            #- Header=X-Request-Id, \d+
            #- Method=GET
            #- Query=name,xushu|zhuge
            #- CheckAuth = xushu
          #filters:
            #- AddRequestHeader=X-Request-color,red
            #- AddRequestParameter=color,blue
            #- PrefixPath=/mall-order #添加前缀对应微服务需要配置context-path
            #- StripPrefix=1 # 转发之前,去掉第一次的路径
            # http://localhost:8020/order/add
            #- RedirectTo=302, https://www.baidu.com
            #- SetStatus= 404
            #- CheckAuth=xushu
        #- id: stock_route
    # 配置Nacos
      # 跨域的配置
 #     globalcors:
 #       cors-configurations:
 #         '[/**]': # 允许跨域访问的资源
 #           allowedOrigins: "*" #跨域允许的来源 例如:www.smsm.com
 #           allowedMethods:
 #             - GET
 #             - POST
 #             - PUT

    #配置Nacos
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        username: nacos
        password: nacos
    # 配置sentinel
    sentinel:
      transport:
        dashboard: 127.0.0.1:8858

3、完善测试接口

下载:sentinel-dashboard-1.8.0.jar

https://github.com/alibaba/Sentinel/releases

运行jar包

xml 复制代码
java -Dserver.port=8858 -Dsentinel.dashboard.auth.username=xushu -Dsentinel.dashboard.auth.password=123456 -jar C:\Users\ZHENG\Desktop\sentinel-dashboard-1.8.0.jar

访问:http://localhost:8858/

账号:xushu

密码:123456


http://127.0.0.1:8088/order/add



访问:http://127.0.0.1:8088/order/add

不断点击连续访问

二、通过代码实现限流

1、编写配置类


java 复制代码
@Configuration
public class GatewayConfig {
    @PostConstruct //设置初始化的时候
    public void init(){
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable t) {
                System.out.println(t);
                HashMap<String,String> map = new HashMap<String,String>();
                map.put("code",HttpStatus.TOO_MANY_REQUESTS.toString());
                map.put("message","限流了");
                //自定义的异常处理
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(map))
                        ;
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

访问:http://127.0.0.1:8088/order/get


访问:http://127.0.0.1:8088/order/get

连续不断访问

三、通过配置文件实现

xml 复制代码
      scg:
        fallback:
          mode: response
          response-body: "{code:'',messageL:''}"

四、网管高可用

为了保证Gateway的高可用性,可以同时启动多个Gateway实例进行负载,在Gateway的.上游使用Nginx或者F5进行负载转发以达到高可用。

相关推荐
LUCIAZZZ11 分钟前
HikariCP数据库连接池原理解析
java·jvm·数据库·spring·springboot·线程池·连接池
sky_ph34 分钟前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
IDRSolutions_CN1 小时前
PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第二部分)
java·经验分享·pdf·软件工程·团队开发
hello早上好1 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
HelloWord~2 小时前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧2 小时前
黑马点评【基于redis实现共享session登录】
java·redis
BillKu3 小时前
Java + Spring Boot + Mybatis 插入数据后,获取自增 id 的方法
java·tomcat·mybatis
全栈凯哥3 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
chxii3 小时前
12.7Swing控件6 JList
java
全栈凯哥3 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表