01 gateway(网关)
1.1 简介
Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。 Spring Cloud Gateway是加在整个微服务最前面的防火墙和代理器,隐藏微服务节点IP与端口信息,从而达到保护微服务的目的。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。
网关结构图:
1.2 说明
不管是来自于客户端(PC或移动端)的请求,还是服务内部调用。一切对服务的请求都可经过网关,然后再由网关来实现鉴权、动态路由等等操作。Gateway就是我们微服务调用的统一入口。
1.3 核心概念
- 路由(route):路由信息的组成: 由一个ID、一个目标URI、一组断言工厂、一组过滤器组成。如果断言为真,该请求就会 路由到 目标URI。
- 断言(Predicate):用断言工厂去匹配请求URL。如果能匹配,断言为真。
- 过滤器(Filter):用过滤器过滤请求,包括: 过滤请求URL、过滤请求参数、过滤请求头等。
02 快速入门
2.1 创建模块
2.2 添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-demo</artifactId>
<groupId>cn.itcast</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-server</artifactId>
<dependencies>
<!-- 配置eureka客户端启动器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 配置gateway启动器(基于netty运行,所在不需要tomcat启动器) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
</project>
2.3 编写启动类
在gateway-server中创建cn.itcast.GatewayApplication启动类
package cn.itcast;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args){
SpringApplication.run(GatewayApplication.class, args);
}
}
2.4 编写配置文件
在gateway-server中创建application.yml文件,内容如下:
server:
port: 10010
spring:
application:
name: api-gateway
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka,http://localhost:8762/eureka
2.5 编写路由规则
修改gateway-server的application.yml文件为(GatewayProperties.java):
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 路由的服务地址
uri: http://127.0.0.1:9001
# 断言,Path: 配置路由映射路径
predicates:
- Path=/user/**
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka,http://localhost:8762/eureka
2.6 启动测试
测试效果如下: