1.搭建网关模块
2.引入依赖:starter-gateway
<dependencies>
<!--引入gateway 网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
3.创建启动类
package com.itheima.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author mcm
*/
@SpringBootApplication
public class ApiGateway {
public static void main(String[] args) {
SpringApplication.run(ApiGateway.class, args);
}
}
4.配置文件
server:
port: 8888
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 自定义规则名称
- id: user-service
uri: http://localhost:8001 #微服务地址
predicates:
# 匹配路径 ** 表示支持多级路径 例如 /user/aa/123 /user/aa/bb/123
# 例如访问 http://localhost:8888/user/123 --> http://localhost:8001/user/123
- Path=/user/**
- id: service-consumer
uri: http://localhost:9001 #微服务地址
predicates:
- Path=/consumer/**
5.Gateway-静态路由配置文件
server:
port: 8888
spring:
application:
name: api-gateway
cloud:
# 网关配置
gateway:
# 路由配置:转发规则
routes: #集合。
# id: 唯一标识。默认是一个UUID
# uri: 转发路径
# predicates: 条件,用于请求网关路径的匹配规则
- id: user-service
uri: http://localhost:8001/
predicates:
- Path=/user/**