基于从前的项目:https://www.cnblogs.com/xsj1989/p/18338930
参考文章:https://blog.csdn.net/hong161688/article/details/140812734
官网文档:https://cloud.spring.io/spring-cloud-gateway/reference/html/
新建一个Module,cloud-gateway-center
pom引入包
<!--SpringCloud服务网关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
main改一下
@SpringBootApplication public class CloudGatewayCenterMain { public static void main(String[] args) { SpringApplication.run(CloudGatewayCenterMain.class, args); } }
bootstrap.yaml配置文件
server: port: 8004 spring: application: # Nacos添加配置,格式:${prefix}-${spring.profiles.active}.${file-extension} name: cloud-gateway-center profiles: active: dev # 配置环境变量,Nacos配置DataId的一部分。自定义例如:dev test pro cloud: nacos: discovery: server-addr: localhost:8848 # Nacos作为服务中心地址 config: server-addr: localhost:8848 # Nacos作为配置中心地址 file-extension: yaml # Nacos配置后缀 group: DEFAULT_GROUP # Nacos配置分组 namespace: 8e23ce60-9f28-4fa7-875a-5e0d61b533d5 # Nacos配置命名空间的id,默认public username: nacos # Nacos登录账户 password: 123456 # Nacos登录密码 gateway: enabled: true # 启用gateway routes: - id: cloud-order-service uri: http://localhost:8001 predicates: - Path=/api/** filters: - StripPrefix=1
启动后,发送请求 http://localhost:8004/api/test/getHobbies?userId=1 被转发为 http://localhost:8001/test/getHobbies?userId=1