gateway整合filters

本文档详细介绍了如何在Spring Cloud Gateway中结合Nacos配置过滤器,特别是针对AddRequestParamter的使用。通过在application.yml中设置路由和过滤器,对请求进行参数添加,但遇到无法找到GatewayFilterFactory的问题。解决方法是检查配置是否正确,并理解过滤器的工作原理,确保请求参数能在转发过程中被正确处理。文中还提供了相关Maven依赖以供参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unable to find GatewayFilterFactory with name AddRequestParamter

首先确定你要做的是用nacos整合gateway,然后使用gateway配置filters对请求进行修改。

一、首先在gateway微服务的application.yml或者bootstrap.yml文件进行filter的配置

// A code block
server:
  port: 8088
spring:
  application:
    name: gateway-test
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: lb://service-consumer #lb代表负载均衡,后面的是你的服务ID
          filters:
          - AddRequestHeader=X-Request-Foo, BarTest #请求头添加X-Request-Foo:BarTest
          - AddResponseHeader=X-Response-Foo, Bar   #响应参数添加X-Response-Foo:Bar
          - AddRequestParameter=foo, bar            #请求参数添加foo:bar
          predicates:  #对在这个时间之后的请求转发到lb://service-consumer
          - After=2019-12-25T14:33:47.789+08:00

二、我们对gateway发起在2019-12-25之后的任何请求都将被转发到我们服务ID为service-consumer的微服务模块。
在这里插入图片描述我发送了请求,并且响应参数里面含有我们在yml文件里面设置的参数。这个请求我们为什么看不到设置的request参数呢?

三、关于我们设置的request参数

在这里插入图片描述我们前面访问的http://localhost:8088/Cus_echo/tests这个请求,就会被网关转发到这个微服务ID为service-consumer的微服务,所以我们在yml文件设置的请求头参数在这里可以获取到。如果要获取请求参数,可以自己获取一下。

maven依赖如下:

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
### Spring Cloud Gateway 整合 Sentinel 的配置教程 #### 一、背景介绍 Spring Cloud Gateway 是基于 Reactor 和 Netty 构建的高性能 API 网关,而 Sentinel 则是一个用于流量防护和服务治理的开源框架。两者结合可以有效保护微服务架构中的资源免受高并发请求的影响。 以下是关于如何将 Spring Cloud Gateway 与 Sentinel 进行整合的具体方法[^4]: --- #### 二、依赖引入 在项目的 `pom.xml` 文件中添加以下 Maven 依赖项: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> ``` 上述依赖会自动集成 Sentinel 功能到 Spring Cloud Gateway 中[^2]。 --- #### 三、核心配置 编辑项目中的 `application.yml` 或 `application.properties` 文件,完成基础配置。以下是一个典型的 YAML 配置示例: ```yaml server: port: 8080 spring: application: name: gateway-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # Nacos 注册中心地址 gateway: routes: - id: example-route uri: lb://example-service predicates: - Path=/api/example/** filters: - StripPrefix=1 sentinel: transport: dashboard: localhost:8081 # Sentinel 控制台地址 ``` 在此配置中,`sentinel.transport.dashboard` 参数指定了 Sentinel 控制台的服务地址。 --- #### 四、自定义过滤器逻辑 为了使 Sentinel 更好地适配 Spring Cloud Gateway,可以通过编写自定义过滤器来增强功能。例如,创建一个全局过滤器类并将其注册到应用上下文中: ```java import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; @Component public class CustomGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 自定义逻辑:可以在进入网关前执行某些操作 String requestPath = exchange.getRequest().getPath().value(); // 将路径传递给 Sentinel 流量统计模块 Entry entry = null; try { entry = SphU.entry(requestPath); return chain.filter(exchange); } catch (BlockException e) { // 当触发限流时返回特定响应 exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } finally { if (entry != null) { entry.exit(); } } } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } } ``` 以上代码片段展示了如何捕获请求路径并通过 Sentinel 的 `Entry` 接口对其进行监控和管理。 --- #### 五、启动类设置 修改应用程序的主入口类,确保其支持 Sentinel 的初始化工作。例如: ```java import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; import com.alibaba.csp.sentinel.slots.block.flow.FlowException; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GatewayApplication { private static final Logger log = LoggerFactory.getLogger(GatewayApplication.class); public static void main(String[] args) { // 设置属性以启用 Sentinel 对于网关的支持 System.setProperty("csp.sentinel.app.type", "1"); SpringApplication.run(GatewayApplication.class, args); log.info(">>> GatewayApplication started successfully <<<"); } /** * 定义异常处理程序以便更好地反馈错误信息 */ public BlockExceptionHandler blockHandler() { return (request, exception, response) -> { if (exception instanceof FlowException || exception instanceof ParamFlowException) { response.setStatus(429); // Too Many Requests } else if (exception instanceof DegradeException) { response.setStatus(503); // Service Unavailable } else if (exception instanceof AuthorityException) { response.setStatus(403); // Forbidden } return response.getWriter().write("{\"error\":\"Blocked by Sentinel\"}"); }; } } ``` 这段代码设置了日志记录机制,并通过 `System.setProperty()` 方法启用了 Sentinel 的特殊模式。 --- #### 六、测试验证 部署完成后,访问目标接口(如 `/api/example/test`),观察是否能够正常调用下游服务;随后调整 Sentinel 控制台上对应的规则参数,确认限流降级策略生效情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值