应用场景:反向代理、鉴权、流量控制、熔断、日志监控
- 导入依赖
- yml配置
- 注册到服务中心
- 过滤器
1、pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
注意:gateway不依赖starter-web,所以去掉spring-boot-web-starter依赖,gateway自带有启动
2、yml配置文件
eureka: client: service-url: defaultZone: http://localhost:7001/eureka #注册到eureka服务中心 instance: prefer-ip-address: true #显示IP spring: application: name: gateway-service #在eureka服务中心名称 cloud: gateway: discovery: locator: enabled: true #开启网关,默认通过服务名称访问到其他服务 routes: #自定义路由规则 - id: user-service-7010 #路由的ID,随便起,建议与服务实例名相同 uri: lb://USER-SERVICE #地址 lb://表示使用负载均衡,或http://localhost:80 predicates: - Path=/producer/huser/** #匹配路由,通过网关转发到lb://USER-SERVICE服务下的/producer/huser/... - id: consumer-api-80 uri: http://localhost:80 predicates: - Path=/consumer/**
3、spring boot启动类加上:@EnableDiscoveryClient
不加会报错,无法找到服务的实例
测试通过微服务自测:http://localhost:7010/producer/huser/xxx
通过网关测试: http://localhost:8010/producer/huser/xxx
访问成功则网关配置成功!
4、网关的过滤器的过滤
@Component
public class GateWayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
System.out.println("过滤请求路径:"+path);
//token校验,登录校验逻辑....
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
最后结果: