Gateway 网关
迪丽瓦拉
2025-05-28 10:22:10
0

Gateway 网关

网关概述

  1. 网关旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。
  2. 在微服务架构中,不同的微服务可以有不同的网络地址,各个微服务之间通过互相调用完成用户请求,客户端可能通过调用N个微服务的接口完成一个用户请求。
  3. 存在的问题:
    4. 客户端多次请求不同的微服务,增加客户端的复杂性
    4. 认证复杂,每个服务都要进行认证
    4. http请求不同服务次数增加,性能不高
  4. 网关就是系统的入口,封装了应用程序的内部结构,为客户端提
    供统一服务,一些与业务本身功能无关的公共逻辑可以在这里实现,
    诸如认证、鉴权、监控、缓存、负载均衡、流量管控、路由转发等
  • 在目前的网关解决方案里,有Nginx+ Lua、Netflix Zuul 、Spring Cloud Gateway等等
    在这里插入图片描述

Gateway 网关快速入门

  1. 搭建网关模块
  2. 引入依赖:starter-gateway
  3. 编写启动类
  4. 编写配置文件
  5. 启动测试
    eureka-server-gateway、gateway-consumer和gateway-provider基础配置跟hystrix一致

创建api-gateway-server

org.springframework.cloudspring-cloud-starter-gatewayorg.springframework.cloudspring-cloud-starter-netflix-eureka-client

在这里插入图片描述

APiGatewayApp.java

package com.itheima.geteway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication
@EnableEurekaClient
public class APiGatewayApp {public static void main(String[] args) {SpringApplication.run(APiGatewayApp.class, args);}
}

application.yml

server:port: 80spring:application:name: api-gateway-servercloud:#网关配置gateway:#路由配置:转发规则routes: #集合# id 唯一标识 默认是UUID# uri 转发路径# predicates 条件,用于请求网关路径的匹配规则- id: gateway-provideruri: http://localhost:8001/predicates:- Path=/goods/**

Gateway 网关路由配置 – 静态路由

server:
port: 80

spring:
application:
name: api-gateway-server

cloud:
#网关配置
gateway:
#路由配置:转发规则
routes: #集合
# id 唯一标识 默认是UUID
# uri 转发路径
# predicates 条件,用于请求网关路径的匹配规则
- id: gateway-provider
uri: http://localhost:8001/ #静态路由
predicates:
- Path=/goods/**

  - id: gateway-consumeruri: http://localhost:9000/ #静态路由predicates:- Path=/order/**

Gateway 网关路由配置 – 动态路由

  1. 引入eureka-client配置
  2. 修改uri属性:uri: lb://服务名称
spring:application:name: api-gateway-servercloud:#网关配置gateway:#路由配置:转发规则routes: #集合# id 唯一标识 默认是UUID# uri 转发路径# predicates 条件,用于请求网关路径的匹配规则- id: gateway-provider#uri: http://localhost:8001/#动态路由uri: lb://GATEWAY-PROVIDERpredicates:- Path=/goods/**- id: gateway-consumer#uri: http://localhost:9000/uri: lb://GATEWAY-CONSUMERpredicates:- Path=/order/**#设置eureka服务端的路径
eureka:client:service-url:defaultZone: http://localhost:8761/eureka

在这里插入图片描述

Gateway 网关路由配置 – 微服务名称配置

spring:  cloud:      discovery:        locator:          enabled: true # 开启微服发现功能          lower-case-service-id: true # 讲请求路径上的服务名配置为小写
server:port: 80spring:application:name: api-gateway-servercloud:#网关配置gateway:#路由配置:转发规则routes: #集合# id 唯一标识 默认是UUID# uri 转发路径# predicates 条件,用于请求网关路径的匹配规则- id: gateway-provider#uri: http://localhost:8001/#动态路由uri: lb://GATEWAY-PROVIDERpredicates:- Path=/goods/**- id: gateway-consumer#uri: http://localhost:9000/uri: lb://GATEWAY-CONSUMERpredicates:- Path=/order/**#微服务名称配置discovery:locator:enabled: true #设置为true 请求路径前可以添加微服务名称lower-case-service-id: true #允许为小写#设置eureka服务端的路径
eureka:client:service-url:defaultZone: http://localhost:8761/eureka

Gateway 过滤器

  1. Gateway 支持过滤器功能,对请求或响应进行拦截,完成一些通用操作。
  2. Gateway 提供两种过滤器方式:“pre”和“post”
  3. pre 过滤器,在转发之前执行,可以做参数校验、权限校验、流量监控、日志输出、协议转换等。
  4. post 过滤器,在响应之前执行,可以做响应内容、响应头的修改,日志的输出,流量监控等。
  5. Gateway 还提供了两种类型过滤器
    GatewayFilter:局部过滤器,针对单个路由
    GlobalFilter :全局过滤器,针对所有路由
    在这里插入图片描述

Gateway 过滤器 – 局部过滤器

  1. GatewayFilter 局部过滤器,是针对单个路由的过滤器。
  2. 在Spring Cloud Gateway 组件中提供了大量内置的局部过滤器,对请求和响应做过滤操作。
  3. 遵循约定大于配置的思想,只需要在配置文件配置局部过滤器名称,并为其指定对应的值,就可以让其生效。
server:port: 80spring:application:name: api-gateway-servercloud:#网关配置gateway:#路由配置:转发规则routes: #集合# id 唯一标识 默认是UUID# uri 转发路径# predicates 条件,用于请求网关路径的匹配规则# filters: 配置局部过滤器- id: gateway-provider#uri: http://localhost:8001/#动态路由uri: lb://GATEWAY-PROVIDERpredicates:- Path=/goods/**filters:- AddRequestParameter=username,zhangsan #key value- id: gateway-consumer#uri: http://localhost:9000/uri: lb://GATEWAY-CONSUMERpredicates:- Path=/order/**#微服务名称配置discovery:locator:enabled: true #设置为true 请求路径前可以添加微服务名称lower-case-service-id: true #允许为小写#设置eureka服务端的路径
eureka:client:service-url:defaultZone: http://localhost:8761/eureka

修改gateway-provider程序

在这里插入图片描述
在这里插入图片描述

package com.itheima.provider.controller;import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.util.Date;/*** Goods Controller 服务提供方*/@RestController
@RequestMapping("/goods")
public class GoodsController {@Autowiredprivate GoodsService goodsService;@Value("${server.port}")private int port;/*** 降级:*  1. 出现异常*  2. 服务调用超时*      * 默认1s超时**  @HystrixCommand(fallbackMethod = "findOne_fallback")*      fallbackMethod:指定降级后调用的方法名称*/@GetMapping("/findOne/{id}")@HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {//设置Hystrix的超时时间,默认1s@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),//监控时间 默认5000 毫秒@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "5000"),//失败次数。默认20次@HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "20"),//失败率 默认50%@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")})public Goods findOne(@PathVariable("id") int id,String username){System.out.println(username);//如果id == 1 ,则出现异常,id != 1 则正常访问if(id == 1){//1.造个异常int i = 3/0;}/*try {//2. 休眠2秒Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}*/Goods goods = goodsService.findOne(id);goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置到了 商品标题上return goods;}/*** 定义降级方法:*  1. 方法的返回值需要和原方法一样*  2. 方法的参数需要和原方法一样*/public Goods findOne_fallback(int id, String username){Goods goods = new Goods();goods.setTitle("降级了~~~");return goods;}}

执行http://localhost/goods/findOne/2 打印
在这里插入图片描述

Gateway 过滤器 – 全局过滤器

  1. GlobalFilter 全局过滤器,不需要在配置文件中配置,系统初始化时加载,并作用在每个路由上。
  2. Spring Cloud Gateway 核心的功能也是通过内置的全局过滤器来完成。
  3. 自定义全局过滤器步骤:
    1 定义类实现 GlobalFilter 和 Ordered接口
    2 复写方法
    3 完成逻辑处理

在这里插入图片描述

package com.itheima.geteway.filter;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;
import reactor.core.publisher.Mono;@Component
public class MyFilter implements GlobalFilter, Ordered {@Overridepublic Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {System.out.println("自定义全局过滤器执行了~~~");return chain.filter(exchange); ///放行}/*** 过滤器排序* @return 数值越小,越先执行*/@Overridepublic int getOrder() {return 0;}
}

在这里插入图片描述

相关内容

热门资讯

linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
C++ 机房预约系统(六):学... 8、 学生模块 8.1 学生子菜单、登录和注销 实现步骤: 在Student.cpp的...
A.机器学习入门算法(三):基... 机器学习算法(三):K近邻(k-nearest neigh...
数字温湿度传感器DHT11模块... 模块实例https://blog.csdn.net/qq_38393591/article/deta...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
Redis 所有支持的数据结构... Redis 是一种开源的基于键值对存储的 NoSQL 数据库,支持多种数据结构。以下是...
win下pytorch安装—c... 安装目录一、cuda安装1.1、cuda版本选择1.2、下载安装二、cudnn安装三、pytorch...
MySQL基础-多表查询 文章目录MySQL基础-多表查询一、案例及引入1、基础概念2、笛卡尔积的理解二、多表查询的分类1、等...
keil调试专题篇 调试的前提是需要连接调试器比如STLINK。 然后点击菜单或者快捷图标均可进入调试模式。 如果前面...
MATLAB | 全网最详细网... 一篇超超超长,超超超全面网络图绘制教程,本篇基本能讲清楚所有绘制要点&#...
IHome主页 - 让你的浏览... 随着互联网的发展,人们越来越离不开浏览器了。每天上班、学习、娱乐,浏览器...
TCP 协议 一、TCP 协议概念 TCP即传输控制协议(Transmission Control ...
营业执照的经营范围有哪些 营业执照的经营范围有哪些 经营范围是指企业可以从事的生产经营与服务项目,是进行公司注册...
C++ 可变体(variant... 一、可变体(variant) 基础用法 Union的问题: 无法知道当前使用的类型是什...
血压计语音芯片,电子医疗设备声... 语音电子血压计是带有语音提示功能的电子血压计,测量前至测量结果全程语音播报࿰...
MySQL OCP888题解0... 文章目录1、原题1.1、英文原题1.2、答案2、题目解析2.1、题干解析2.2、选项解析3、知识点3...
【2023-Pytorch-检... (肆十二想说的一些话)Yolo这个系列我们已经更新了大概一年的时间,现在基本的流程也走走通了,包含数...
实战项目:保险行业用户分类 这里写目录标题1、项目介绍1.1 行业背景1.2 数据介绍2、代码实现导入数据探索数据处理列标签名异...
记录--我在前端干工地(thr... 这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 前段时间接触了Th...
43 openEuler搭建A... 文章目录43 openEuler搭建Apache服务器-配置文件说明和管理模块43.1 配置文件说明...