第一步:
创建网关模块
第二部:
引入依赖
<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>
</dependency>
</dependencies>
第三步:
编写启动类
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
第四步:
配置路由
server:
port: 8080
spring:
application:
name: gateway
profiles:
active: dev
cloud:
nacos:
server-addr: nacos所处的地址
gateway:
routes:
- id: item-service # 路由规则id,自定义,唯一
uri: lb://item-service #路由目标微服务,lb代表负载均衡
predicates: #路由断言,判断请求是否符合规则,符合则路由到目标
- Path=/items/**,/search/** # 以请求路径做判断,以/items或者/search开头则符合
, 表示或者,即如果需要多个路径就可以加,隔开继续添加
- id: user-service
uri: lb://user-service
predicates:
- Path=/addresses/**,/users/**
logging:
level:
com.hmall: debug
pattern:
dateformat: HH:mm:ss:SSS
file:
path: "logs/${spring.application.name}"
路由断言:
用的最多的就是path,也会用header做灰度测频率也很低)