一、简单介绍
Spring Cloud Gateway 是 Spring 生态中一个基于响应式编程模型构建的 API 网关,用于在微服务架构中统一管理外部请求的入口,并提供路由、过滤、限流等核心功能
二、简单使用方法
1、创建网关项目

2、引入网关依赖
<dependencies> <!--⽹关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!--基于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-loadbalancer</artifactId> </dependencies>
3、编写启动类
java
package com.linzhixin.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4、添加 Gateway 的路由配置
server:
port: 10030 # 网关端⼝
spring:
application:
name: gateway # 服务名称
cloud:
nacos:
discovery:
server-addr: XXXXXXX
gateway:
routes: # 网关路由配置
- id: order-service #路由ID, 自定义, 唯⼀即可
uri: lb://order-service
predicates: #路由条件
Path=/order/**, /feign/**
id: product-service #路由ID, 自定义, 唯⼀即可
uri: lb://product-service #目标服务地址
predicates: #路由条件
- Path=/product/**
5、测试
通过网关服务访问 product-servicehttp://127.0.0.1:10030/product/1001
三、深入学习
关于 Predicate、Filter等的详细用法见官方文档