Cloud整合GateWay+过滤器

这篇博客介绍了如何在Spring Cloud Gateway中进行反向代理、鉴权、流量控制和熔断等操作,并通过YAML配置、@EnableDiscoveryClient注解实现服务注册。内容包括去除spring-boot-starter-web依赖、添加过滤器以及测试网关和微服务的正确配置和工作流程。

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

 应用场景:反向代理、鉴权、流量控制、熔断、日志监控

  1. 导入依赖
  2. yml配置
  3. 注册到服务中心
  4. 过滤器

1、pom依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

注意:gateway不依赖starter-web,所以去掉spring-boot-web-starter依赖,gateway自带有启动

 

 2、yml配置文件

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka #注册到eureka服务中心
  instance:
    prefer-ip-address: true #显示IP

spring:
  application:
    name: gateway-service #在eureka服务中心名称
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #开启网关,默认通过服务名称访问到其他服务
      routes:  #自定义路由规则
        - id: user-service-7010 #路由的ID,随便起,建议与服务实例名相同
          uri: lb://USER-SERVICE #地址 lb://表示使用负载均衡,或http://localhost:80
          predicates:
            - Path=/producer/huser/**   #匹配路由,通过网关转发到lb://USER-SERVICE服务下的/producer/huser/...
        - id: consumer-api-80
          uri: http://localhost:80
          predicates:
            - Path=/consumer/**

 3、spring boot启动类加上:@EnableDiscoveryClient 

 不加会报错,无法找到服务的实例

测试通过微服务自测:http://localhost:7010/producer/huser/xxx

通过网关测试: http://localhost:8010/producer/huser/xxx

访问成功则网关配置成功! 

 4、网关的过滤器的过滤

@Component
public class GateWayFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("过滤请求路径:"+path);
        

        //token校验,登录校验逻辑....

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

最后结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JBoying

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值