Gateway(路由映射)

1.SpringCloud Gateway

Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。

Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息,从而加强安全保护。

Spring Cloud Gateway本身也是一个微服务,需要注册进服务注册中心

三个核心

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

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

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

web前端请求,通过一些匹配条件,定位到真正的服务节点。并在这个转发过程的前后,进行一些精细化控制。

predicate就是我们的匹配条件;

filter,就可以理解为一个无所不能的拦截器。有了这两个元素,再加上目标uri,就可以实现一个具体的路由了

工作流程

路由转发+断言判断+执行过滤器链

客户端向 Spring Cloud Gateway 发出请求。然后在 Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到 Gateway Web Handler。Handler 再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。

过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(Pre)或之后(Post)执行业务逻辑。

在"pre"类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等;

在"post"类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量监控等有着非常重要的作用

2.入门配置

导入依赖:

XML 复制代码
 <dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--服务注册发现consul discovery,网关也要注册进服务注册中心统一管控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!-- 指标监控健康检查的actuator,网关是响应式编程删除掉spring-boot-starter-web dependency-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

编写yml文件:

XML 复制代码
server:
  port: 9527

spring:
  application:
    name: cloud-gateway #以微服务注册进consul或nacos服务列表内
  cloud:
    consul: #配置consul地址
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true
        service-name: ${spring.application.name}

启动类开启注解

3.网关映射

被调用模块新建测试类:
java 复制代码
package com.wen.cloud.controller;

import cn.hutool.core.util.IdUtil;;
import com.wen.cloud.entities.Pay;
import com.wen.cloud.resp.ResultData;
import com.wen.cloud.service.PayService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayGateWayController
{
    @Resource
    PayService payService;

    @GetMapping(value = "/pay/gateway/get/{id}")
    public ResultData<Pay> getById(@PathVariable("id") Integer id)
    {
        Pay pay = payService.getById(id);
        return ResultData.success(pay);
    }

    @GetMapping(value = "/pay/gateway/info")
    public ResultData<String> getGatewayInfo()
    {
        return ResultData.success("gateway info test:"+ IdUtil.simpleUUID());
    }
}
gateway模块yml文件配置
XML 复制代码
spring:
  application:
    name: cloud-gateway #以微服务注册进consul或nacos服务列表内
  cloud:
    consul: #配置consul地址
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true
        service-name: ${spring.application.name}
    gateway:
      routes:
        - id: pay_routh1 #pay_routh1                #路由的ID(类似mysql主键ID),没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001                #匹配后提供服务的路由地址
          predicates:
            - Path=/pay/gateway/get/**

        - id: pay_routh2 #pay_routh2                #路由的ID(类似mysql主键ID),没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001                #匹配后提供服务的路由地址
          predicates:
            - Path=/pay/gateway/info/**              # 断言,路径相匹配的进行路由
模拟测试:

地址+9527(网关端口)+调用服务的路由地址:

4.访问路径:先找网关后找服务

请求通过feign映射到gateway网关 网关通过配置匹配到被调用的模块方法。

feign调用模块:
java 复制代码
package com.wen.cloud.controller;

import com.wen.cloud.apis.PayGatewayFeignApi;
import com.wen.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderGatewayController {

    @Resource
    PayGatewayFeignApi payGatewayFeignApi;

    @GetMapping("/gateway/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id)
    {
        System.out.println("-------寻找网关匹配后调用服务");
        ResultData resultData = payGatewayFeignApi.getById(id);
        return resultData;
    }

    @GetMapping("/gateway/pay/info")
    public String getInfo()
    {
        System.out.println("-------寻找网关匹配后调用服务");

        return  payGatewayFeignApi.getInfoByConsul();
    }
}
feign接口

将调用feign接口的请求转发给网关

java 复制代码
package com.wen.cloud.apis;

import com.wen.cloud.resp.ResultData;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "cloud-gateway")
public interface PayGatewayFeignApi {
    @GetMapping("/pay/gateway/info")
    public String getInfoByConsul();

    @GetMapping(value = "/pay/gateway/get/{id}")
    public ResultData getById(@PathVariable("id") Integer id);
}
被调用模块

通过网关的配置将请求匹配到该模块的方法体中

java 复制代码
package com.wen.cloud.controller;

import cn.hutool.core.util.IdUtil;;
import com.wen.cloud.entities.Pay;
import com.wen.cloud.resp.ResultData;
import com.wen.cloud.service.PayService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayGateWayController
{
    @Resource
    PayService payService;

    @GetMapping(value = "/pay/gateway/get/{id}")
    public ResultData<Pay> getById(@PathVariable("id") Integer id)
    {
        System.out.println("通过网关匹配到该模块方法");
        Pay pay = payService.getById(id);
        return ResultData.success(pay);
    }

    @GetMapping(value = "/pay/gateway/info")
    public ResultData<String> getGatewayInfo()
    {
        System.out.println("通过网关匹配到该模块方法");
        return ResultData.success("gateway info test:"+ IdUtil.simpleUUID());
    }
}
当有网关时
当网关停止时:
相关推荐
就改了13 分钟前
SpringBoot 自定义线程池 + 实时监控指标
java·spring boot·后端
plainGeekDev21 分钟前
运行时获取依赖 → 编译时注入
android·java·kotlin
玖石书2 小时前
ASP.NET Core 迁移至 Spring系列:类库框架篇
java·后端·asp.net
笨蛋不要掉眼泪2 小时前
RabbitMQ消息队列:延迟消息
java·rabbitmq·java-rabbitmq
Adios7942 小时前
搜索二维矩阵 II
java·数据结构·算法
摇滚侠2 小时前
《SpringBoot 3:入门与应用实战》第 15 章 生产级特性 监控指标 Metrics 阅读笔记
java·spring boot·笔记
骇客野人3 小时前
IDEA 安装 Trae(TRAE AI: Coding Assistant)完整步骤
java·ide·intellij-idea
弹简特3 小时前
【Java项目-企悦抽】11-用户与认证模块-实现用户登录03(结束登录功能)-完成测试+对接前端+登录拦截器
java·开发语言
大模型丫丫3 小时前
Loop Engineering:从强化学习视角看 Agent 循环的本质
java·人工智能·学习
数电发票API3 小时前
税局接口,需要的来~~
java