SpringCloud GateWay网关-学习笔记

简介: SpringCloud GateWay网关-学习笔记

1,概述

一句话总结:SpringCloud Gateway使用的是Webflux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架。

源码架构

2,gateway能做什么

反向代理
      鉴权
      流量控制
      熔断
      日志监控
      ...

3,微服务中的网关位置


非阻塞异步!非阻塞异步!非阻塞异步!


4,三大核心概念

路由(route)

路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由

断言(predicate)

参考的是Java8的java.util.function.Predicate

开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由

过滤(filter)

指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改.

总体:

5,gateway工作流程

核心逻辑 : 路由转发+执行过滤器链

6,Gateway网关路由有两种配置方式:

在配置文件yaml中配置:
server:
  port: 9527
spring:
  application:
    name: cloud-gateway-service
  cloud:
    gateway:
      routes:                                     #多个路由
        - id: payment_routh                       #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #          uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service         #路由的ID,没有固定规则但要求唯一,建议配合服务名
          predicates:                             #断言
            - Path=/payment/getById/**                #断言 路径相匹配的进行路由
        - id: payment_routh2
          #          uri: http://localhost:8001
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**
      discovery:
        locator:
          enabled: true  #开启从注册中心动态生成路由的功能,用微服务名进行路由
eureka:
  instance:
    hostname: cloud_gateway_service
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/
代码中注入RouteLocator的Bean
package com.tigerhhzz.springcloud.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author tigerhhzz
 * @date 2022/6/16 11:29
 */
@Configuration
public class GateWayConfig {
    /*
    * 配置了一个id为route-name的路由规则
    * 当访问地址http://localhost:9527/guonei时自动转发到地址:http://news.baidu.com/guonei
    * */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route",r->r.path("/guonei").uri("http://news.baidu.com/guonei"));
        routes.route("path_route1",r->r.path("/guoji").uri("http://news.baidu.com/guoji"));
        return routes.build();
    }
}

7,开启注册中心动态创建路由,通过服务名实现动态路由

9527服务中的yml配置

8,常用的8种gateway路由断言(Route Predicate)

curl测试请求(携带cookie的例子)

C:\Users\Administrator>curl http://localhost:9527/payment/lb
{"timestamp":"2022-06-16T12:37:14.285+0000","path":"/payment/lb","status":404,"error":"Not Found","message":null,"requestId":"ee95c33b"}
C:\Users\Administrator>curl http://localhost:9527/payment/lb --cookie "username=tigerhhzz"
8001
C:\Users\Administrator>curl http://localhost:9527/payment/lb --cookie "username=tigerhhzz"
8002
C:\Users\Administrator>curl http://localhost:9527/payment/lb --cookie "username=tigerhhzz"
8001
C:\Users\Administrator>curl http://localhost:9527/payment/lb --cookie "username=tigerhhzz"
8002
C:\Users\Administrator>curl http://localhost:9527/payment/lb --cookie "username=tigerhhzz"
8001
C:\Users\Administrator>

断言yml配置参考

总结:Predicate就是为了实现一组匹配规则, 让请求过来找到对应的Route进行处理!!

9,Filter的使用

实现两个接口 implments GlobalFilter,OrderId

filter的作用是 全局日志记录和统一网关鉴权 等等等

自定义过滤器

package com.tigerhhzz.springcloud.filter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
/**
 * @author tigerhhzz
 * @date 2022/6/16 21:05
 */
@Component
public class MyGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("**************come in MylogGateWayGilter:  " + new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null) {
            System.out.println("********用户名为空,非法用户。");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
}

测试地址:http://localhost:9527/payment/lb?uname=z3

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
目录
相关文章
|
6月前
|
存储 缓存 负载均衡
Gateway 网关坑我! 被这个404 问题折腾了一年?
小富分享了一个困扰团队一年多的 SpringCloud Gateway 路由 404 问题。通过日志追踪和源码分析,发现是网关在 Nacos 配置更新后未能正确清理旧的路由权重缓存,导致负载均衡时仍使用已删除的路由数据。最终通过监听路由刷新事件并手动更新缓存,成功解决了问题。
1081 125
Gateway 网关坑我! 被这个404 问题折腾了一年?
|
6月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
5月前
|
缓存 JSON NoSQL
别再手写过滤器!SpringCloud Gateway 内置30 个,少写 80% 重复代码
小富分享Spring Cloud Gateway内置30+过滤器,涵盖请求、响应、路径、安全等场景,无需重复造轮子。通过配置实现Header处理、限流、重试、熔断等功能,提升网关开发效率,避免代码冗余。
592 1
|
5月前
|
机器学习/深度学习 Kubernetes API
【Azure APIM】自建网关(self-host gateway)收集请求的Header和Body内容到日志中的办法
在Azure API Management中,通过配置trace策略可完整记录API请求的Header和Body信息。在Inbound和Outbound策略中分别使用context.Request/Response.Headers和Body.As&lt;string&gt;方法捕获数据,并写入Trace日志,便于排查与审计。
190 8
|
7月前
|
安全 虚拟化
Omnissa Secure Email Gateway 2.33 - 电子邮件网关
Omnissa Secure Email Gateway 2.33 - 电子邮件网关
158 0
|
8月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
590 0
|
9月前
|
缓存 监控 Java
说一说 SpringCloud Gateway 堆外内存溢出排查
我是小假 期待与你的下一次相遇 ~
1261 5
|
9月前
|
应用服务中间件 网络安全 数据安全/隐私保护
网关服务器配置指南:实现自动DHCP地址分配、HTTP服务和SSH无密码登录。
哇哈哈,道具都准备好了,咱们的魔术秀就要开始了。现在,你的网关服务器已经魔法满满,自动分配IP,提供网页服务,SSH登录如入无人之境。而整个世界,只会知道效果,不会知道是你在幕后操控一切。这就是真正的数字世界魔法师,随手拈来,手到擒来。
471 14
|
监控 负载均衡 安全
微服务(五)-服务网关zuul(一)
微服务(五)-服务网关zuul(一)
|
安全 5G 网络性能优化
深入理解5G中的SAEGW:服务网关边界
【10月更文挑战第9天】
588 0