Spring Cloud Gateway 网关(五)

目录

一 概念引入

二 具体使用

1 首先创建一个网关模块

2 启动类

3 配置类

4 对应方法的修改

5 展示借助81端口进行转发控制

6 断言规则​编辑

三 过滤器

1 将前置的请求参数给过滤掉,降低繁琐程度。

2 默认过滤器

3 全局过滤器

4 自定义过滤器工厂

5 全局跨域问题


一 概念引入

Spring Cloud Gateway :: Spring Cloud Gateway

二 具体使用

1 当前主流更多使用的是Reactive Server ,而ServerMVC是老版本的网关。

前景引入:

LoadBalancer:服务内部调用时的负载均衡。

Gateway 负载均衡:系统对外统一入口的负载均衡,内部也会用 LoadBalancer。

        <!--   添加nacos注册中心     --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--   添加网关的依赖     --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- 请求的负载均衡 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency>

实现:

1 首先创建一个网关模块

2 启动类

package com.ax.gateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient
@SpringBootApplication
public class GatewayMainApplication {public static void main(String[] args) {SpringApplication.run(GatewayMainApplication.class, args);}
}

3 配置类

借助的就是81端口的网关进行映射

spring:profiles:include: routeapplication:name: gatewaycloud:nacos:server-addr: 127.0.0.1:8848
server:port: 81
spring:cloud:gateway:routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**- id: last-routeuri: https://cn.bing.com/predicates:- Path=/**

4 对应方法的修改

需要以规范的格式开头(加上api/order或者api/product)

package com.ax.product.controller;import com.ax.product.bean.Product;
import com.ax.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.math.BigDecimal;@Slf4j
@RequestMapping("/api/product")
@RestController
public class ProductController {@Autowiredprivate ProductService productService;// 获取商品信息@GetMapping("/product/{id}")public Product getProduct(@PathVariable("id") Long id) {log.info("getProduct:{}", id);return productService.getProductById(id);}
}

对应的远程调用,这里有一个语法版本兼容问题不能在类的头部写@RequestMapping

package com.ax.order.feign;import com.ax.order.feign.fallback.ProductFeignClientFallback;
import com.ax.product.bean.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;@FeignClient(name = "service-product", fallback = ProductFeignClientFallback.class)
public interface ProductFeignClient {/*** 测试FeignClient** @param id*///mvc注解两套使用逻辑//标注在Controller上,为接收请求//标注在FeignClient上,为发送请求@GetMapping("/api/product/product/{id}")Product getProductById(@PathVariable("id") Long id);//如果调用自己其他服务的api直接将其方法复制过来即可,下面这个就是从product当中复制过来的//    @GetMapping("/product/{id}")//    Product getProduct(@PathVariable("id") Long id);
}

5 展示借助81端口进行转发控制


6 断言规则

三 过滤器

1 将前置的请求参数给过滤掉,降低繁琐程度。

举例说明:路径重写(此时就可以将原先的@RequestMapping当中的参数给去除掉)

spring:cloud:gateway:routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**order: 0filters:- RewritePath=/api/order/(?<segment>.*), /$\{segment}- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**order: 1filters:- RewritePath=/api/product/(?<segment>.*), /$\{segment}- id: last-routeuri: https://cn.bing.compredicates:- Path=/**order: 2

实现目的,就是说如果请求的前缀固定含有某些内容,我们就可以借助这个过滤器将这些请求前缀给过滤掉,比如说访问路径http://localhost:81/api/product/product/1

但是后端接收就可以按照 http://localhost:81/product/1来进行接收,(暂时感觉)也就简化了一个@RequestMapping的注解

2 默认过滤器

使用 default-filters 可以全局加响应头

spring:cloud:gateway:routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**order: 0filters:- RewritePath=/api/order/(?<segment>.*), /$\{segment}- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**order: 1filters:- RewritePath=/api/product/(?<segment>.*), /$\{segment}- id: last-routeuri: https://cn.bing.compredicates:- Path=/**order: 2default-filters:- AddResponseHeader=X-Response-Abc, 123

携带了一个响应头参数

3 全局过滤器

代码展示:

package com.ax.gateway.filter;import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;@Slf4j
@Component
public class RtGlobalFilter implements GlobalFilter, Ordered {/*** 全局过滤器** @param exchange* @param chain* @return*/@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();String path = request.getPath().toString();long startTime = System.currentTimeMillis(); // 记录开始时间log.info("请求开始: path={}, startTime={}", path, startTime);return chain.filter(exchange).doFinally(signalType -> {long endTime = System.currentTimeMillis(); // 记录结束时间long duration = endTime - startTime;      // 计算耗时log.info("请求结束: path={}, endTime={}, 耗时: {}ms", path, endTime, duration);});}/*** 优先级** @return*/@Overridepublic int getOrder() {return 0;}
}

示例:

4 自定义过滤器工厂

自定义过滤器工厂(拦截器的名称也有特殊要求)Spring Cloud Gateway 要求自定义过滤器工厂的类名必须以 GatewayFilterFactory 结尾。

package com.ax.gateway.filter;import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.util.UUID;@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {@Overridepublic GatewayFilter apply(NameValueConfig config) {return new GatewayFilter() {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//每次响应之前添加一个一次性令牌return chain.filter(exchange).then(Mono.fromRunnable(() -> {ServerHttpResponse response = exchange.getResponse();HttpHeaders headers = response.getHeaders();String value = config.getValue();if ("uuid".equalsIgnoreCase(value)) {value = UUID.randomUUID().toString();}if ("jwt".equalsIgnoreCase(value)) {value = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY" +"3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3NTY1NDA" +"xMTksImFkbWluIjp0cnVlLCJyb2xlcyI6WyJ1c2VyIiwiYWRtaW4iX" +"SwiZW1haWwiOiJqb2huLmRvZUBleGFtcGxlLmNvbSJ9.SflKxwRJSMeKKF" +"2QT4fwpMeJf36POk6yJV_adQssw5c";}headers.add(config.getName(), value);}));}};}
}

配置文件(OnceToken....)

spring:cloud:gateway:routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**order: 0filters:- RewritePath=/api/order/(?<segment>.*), /$\{segment}- OnceToken=X-Response-Token,uuid- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**order: 1filters:- RewritePath=/api/product/(?<segment>.*), /$\{segment}- id: last-routeuri: https://cn.bing.compredicates:- Path=/**order: 2default-filters:- AddResponseHeader=X-Response-Abc, 123

结果展示

5 全局跨域问题

全局跨域(CORS)问题 主要是与前端请求不同源的后端接口时,如何解决跨域问题(Cross-Origin Resource Sharing, CORS)。Spring Cloud Gateway 作为网关,它通常会充当微服务之间的流量调度中心,并需要解决跨域请求的问题,确保前端可以安全地与后端进行交互。

代码实现:

spring:cloud:gateway:globalcors:cors-configurations:'[/**]':allowed-origin-patterns: '*'allowed-headers: '*'allowed-methods: '*'routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**order: 0filters:- RewritePath=/api/order/(?<segment>.*), /$\{segment}- OnceToken=X-Response-Token,uuid- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**order: 1filters:- RewritePath=/api/product/(?<segment>.*), /$\{segment}- id: last-routeuri: https://cn.bing.compredicates:- Path=/**order: 2default-filters:- AddResponseHeader=X-Response-Abc, 123

结果展示:

补充:

如何理解网关的负载均衡与微服务之间的负载均衡

第一个是客户端与网关之间的请求

第二个是各个微服务应用之间的请求

可以梳理为 两层负载均衡

  1. 第一层:网关层 LB(入口层)

    • 作用于所有外部请求

    • 只管把流量合理分配到下游微服务实例

  2. 第二层:服务调用层 LB(内部层)

    • 作用于服务之间的 RPC 调用

    • 解决微服务内部调用的流量分配问题

微服务之间的调用可以不过网关,但是如果微服务之间的调用也想借助网关,那么可以在远程调用的微服务名称的指定时,将名称修改为对应的网关服务名称。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/95305.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/95305.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

产品经理操作手册(8)——业务需求文档(BRD)

一、BRD的定义与价值 **业务需求文档(BRD)**是产品开发前期的基础性文档&#xff0c;它将业务诉求转化为结构化的产品需求&#xff0c;是连接业务方与交付团队的桥梁。“BRD不仅是一份文档&#xff0c;而是一个对齐的过程。”BRD核心价值 统一认知&#xff1a;确保各方对业务目…

Excel表格多级下拉选项,如何制作?

之前分享过如何设置下拉选项&#xff0c;但那只是简单的一级下拉菜单&#xff0c;今天再给大家分享多级下拉菜单如何制作。也就是根据前面的下拉选项改变后面的选项。 我们现来复习一级下拉菜单&#xff0c;再接着讲多级下拉菜单 一级下拉选项 首先我们先将表格内容凑填写好…

[Sync_ai_vid] 唇形同步评判器 | 图像与视频处理器 | GPU测试

第4章&#xff1a;SyncNet唇形同步评判器 在前几章中&#xff0c;我们了解了唇形同步推理流程如何协调生成唇形同步视频&#xff0c;以及音频特征提取器(Whisper)如何为LatentSync UNet提供关键音频线索。 UNet利用这些线索巧妙调整唇部动作。但我们如何判断UNet的生成效果&a…

算法:插入排序

插入排序&#xff08;直接插入排序&#xff09; 是一种基于“插入”的排序 思路 它的核心思想是把数组分成两部分&#xff1a;一部分是有序区&#xff0c;另一部分是乱序区也就是待排序区。 每次从未排序部分“取出”一个元素&#xff0c;插入到前半部分合适的位置&#xff0c;…

MCP Go SDK

MCP Go SDK v0.3.0 Open in GitHub Codespaces &#xff08;在 GitHub Codespaces 中打开&#xff09; BREAKING CHANGES &#xff08;重大变更&#xff09; This version contains breaking changes. See the release notes for details PkgGoDev &#xff08;Go 官方包文档入…

面试问题详解十一:Qt中的线程池与 QRunnable

在 Qt 中&#xff0c;多线程的使用是开发高性能 GUI 应用的重要组成部分。为了避免频繁创建和销毁线程带来的资源消耗&#xff0c;Qt 提供了 线程池&#xff08;QThreadPool&#xff09; 和 可运行任务&#xff08;QRunnable&#xff09; 的机制&#xff0c;帮助我们更加高效地…

spring-ai-alibaba-deepresearch 学习(五)——BackgroundInvestigationNode

本篇为spring-ai-alibaba学习系列第三十一篇前面介绍 rewrite_multi_query 节点最后会根据用户上传文件标识 user_upload_file 决定下一节点现在来看一下第二个分支&#xff0c;当 user_upload_file 为 false 时&#xff0c;转入 background_investigator 节点该节点主要是负责…

ESP32S3:开发环境搭建、VSCODE 单步调试、Systemview 分析任务运行情况

目标: 实现点灯工程&#xff0c;并且可以基于 vscode 进行单步调试与 systemview 来分析任务运行情况。 环境搭建 如需在 ESP32-S3 上使用 ESP-IDF&#xff0c;请安装以下软件&#xff1a; 设置 工具链&#xff0c;用于编译 ESP32-S3 代码&#xff1b;编译构建工具 —— CMa…

linux系统学习(6.软件包管理)

目录 一、概述 1.分类 2.命名方式 3.一个软件包的组成 1. 软件包的基本定义 2. 一个软件包通常包含的部分 ① 程序文件 ② 库文件 ③ 配置文件 ④ 数据文件 / 资源文件 ⑤ 文档 / 帮助信息 ⑥ 服务脚本 / 单元文件&#xff08;如果是服务型软件&#xff09; ⑦ 包的…

数据结构青铜到王者第八话---队列(Queue)

目录 一、队列(Queue) 1、概念 2、队列的使用 3、队列模拟实现 4、循环队列 4.1数组下标循环的小技巧&#xff08;1&#xff09;下标最后再往后(offset 小于 array.length): index (index offset) % array.length 4.2如何区分空与满 4.3设计循环队列 二、双端队列 (Deq…

Windows系统之不使用第三方软件查看电脑详细配置信息

MENU使用系统信息工具&#xff08;最详细&#xff09;使用命令行查看命令提示符PowerShell&#xff08;信息更丰富&#xff09;使用DirectX诊断工具&#xff08;查看显卡和声音设备&#xff09;查看设备管理器&#xff08;查看硬件驱动&#xff09;一条命令合集&#xff08;Pow…

K8s学习笔记(一)——

一、k8s是什么一个分布式原来是主要用来管理容器的呀&#xff08;专业点叫“容器编排”&#xff09;&#xff0c;什么是管理&#xff1f;其实就是增删改查等等&#xff0c;简单来理解&#xff0c;k8s就是实现容器增删改查的呗。是开源的&#xff0c;在Linux系统下。就跟创建的s…

Zynq开发实践(FPGA之平台免费IP)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】和c语言平台提供posix api一样&#xff0c;一般fpga厂家也会提供各种各样免费的ip给客户使用。这样&#xff0c;客户就不需要自己去写每一个ip了&am…

nginx 配置文件初识全局块、events、http、server、location 的层级关系

Nginx 配置其实只有两类指令&#xff1a; 放在“某个块”里的块级指令&#xff1b;直接写在顶层的全局指令。 把全部配置想象成一个树形结构&#xff0c;根节点叫 main&#xff0c;往下依次分叉即可。下面用 1 张 ASCII 树 1 张极简示例&#xff0c;30 秒就能看懂层级关系。 层…

OCR大模型最新研究

最新OCR大模型介绍1.GPT-4o 2024.5.14 3.MinerU 2024.7.4 3.GOT-OCR 2024.9.3 4.InternVL3-78B 2025.4.11 开源 通用多模态大模型&#xff0c;OCR是它们的能力之一 因其训练数据的偏向&#xff0c;在文档理解、数学公式识别、图表分析等任务上通常是开源模型中的SOTA&a…

php电子签名

原理使用一对公钥和私钥&#xff0c;用私钥对数据进行签名&#xff0c;用公钥对签名数据进行加密&#xff0c;形成电子签名。电子签名认证&#xff0c;用私钥解密数据&#xff0c;用公钥验证签名。若加密容过长&#xff0c;则将加密内容按照固定长度分块&#xff0c;对每块进行…

鸿蒙Harmony-从零开始构建类似于安卓GreenDao的ORM数据库(三)

目录 一,插入单条数据 二,批量插入数据 三,根据条件删除数据 四,传入对象删除数据 五,删除整张表的数据 六,根据条件更新数据 前面两个章节数据库的创建以及数据库表的创建都已经完成了,下面我们再来看看数据库的增删改查如何构建。 一,插入单条数据 我们先来看一下官…

年度优质会议推荐:【西安石油大学主办|IEEE出版|往届均EI】第七届智能控制、测量与信号处理国际学术会议 (ICMSP 2025)

第七届智能控制、测量与信号处理国际学术会议 (ICMSP 2025) 2025 7th International Conference on Intelligent Control, Measurement and Signal Processing (ICMSP 2025) 2025年11月28-30日 中国北京 主办单位&#xff1a;西安石油大学 会议详情&#xff1a;请点击 亮…

isp 图像处理--DPC坏点矫正

一&#xff0c;Bayer pattern简要介绍我们平时所看到的彩色图像每个像素有三个分量组成&#xff0c;分别为红绿蓝。而目前广泛用到的成像传感器为CMOS传感器&#xff0c;其输出的数据格式为每个像素点只有一个颜色分量&#xff0c;一般称为Bayer Pattern数据&#xff0c;格式如…

Redis常见数据类型及应用场景

好的&#xff0c;我们来详细讲解 Redis 的数据结构及其应用场景。Redis 的强大之处不仅仅在于它支持简单的键值对&#xff0c;更在于它提供了丰富的数据结构&#xff0c;每种结构都针对特定类型的应用场景进行了优化。 核心数据结构与应用场景 Redis 主要支持以下五种核心数据结…