一 Gateway网关
1 介绍
在分布式集群中,前端直接调用多个后端服务需记忆大量独立地址,且服务地址变更时维护成本极高;通过引入 Gateway 网关 作为统一入口,前端仅需记住网关地址(如 http://gateway.example.com),所有请求由网关根据路径或参数智能转发至目标服务;
网关依赖 服务注册与发现机制(如 Nacos/Eureka)动态感知后端服务实例地址,即使服务扩容、迁移或下线,也能实时更新路由信息,确保请求准确送达;这种架构彻底解耦了前端与后端服务的直接依赖,显著降低系统维护复杂度,提升集群的灵活性与可扩展性。
2 新建模块
3 引入依赖 – gateway.pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.tj</groupId>
<artifactId>cloud-play</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>gateway</artifactId>
<dependencies>
<!--路由转发还需要使用注册中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--响应式编程网关(不加mvc标志)-->
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>annotationProcessor</scope>
</dependency>
</dependencies>
</project>
4 创建主启动类 – GatewayMainApplication
// 开启服务发现
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayMainApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayMainApplication.class, args);
}
}
5 配置文件 – gateway.application.yml
spring:
application:
# 该应用的名字
name: gateway
cloud:
nacos:
# nacos地址
server-addr: 127.0.0.1:8848
# 网关端口设置为 80 此时可以不写端口号(因为 HTTP 协议:默认使用 80 端口。)
server:
port: 80
6 启动网关服务上线
二 规则配置
1 新建路由规则配置文件 – application-route.yml
① 路由规则文件 application-route.yml
spring:
cloud:
gateway:
# 路由规则表 List
routes:
# - 表示为List中的一个元素
- id: order-route # 订单请求路由名
uri: lb://service-order # lb 为负载均衡(Load Balancer)前缀格式
predicates: # 断言 符合规定的请求进行转发
- Path=/api/order/** # 请求路径开头相符转给 service-order
- id: product-route # 商品请求路由名