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进行负载转发以达到高可用。

相关推荐
非优秀程序员19 小时前
第04章 邮箱大战,163 与 QQ 的暗战|《互联网产品恩仇录》
java·vue.js·架构
知已难寻19 小时前
Docker 入门:容器技术与 Docker 基础
java·运维·服务器·docker·云原生·容器
文丑颜不良啊21 小时前
LeetCode2481~2500题目解析
java·leetcode
Flynn Liang1 天前
同一需求三套写法:用 Spring AI、LangChain4j、AgentScope Java 各实现一个带工具调用的 RAG 助手(实战对比)
java·人工智能·大模型·架构设计·spring ai·langchain4j·agentscope
聪明的笨猪猪1 天前
实际工程问题:AI 生成 Spring Cache(@Cacheable / @CachePut / @CacheEvict)缓存注解踩坑
java·经验分享·面试·ai编程
愿有所息1 天前
记一次 ARM64 + JDK8 上 fastjson2 的诡异数据错乱
java
秋饼1 天前
MCP 2026-07-28 无状态协议大改版:Spring AI 2.1 多轮往返请求与网关路由落地
java·ai·技术分享·后端开发
SL_staff1 天前
JVS-BI 实战:业务人员如何用零代码 ELT + 可视化配置构建实时经营分析闭环
java·spring·全栈
SL_staff1 天前
企业AI落地难?JVS-AI渐进式实践:安全可控、小切口验证、标准化沉淀与规模化复制
java·开源·aigc
SL_staff1 天前
JVS数字底座实践:构建企业级统一内容管理平台的技术路径
java·产品