一、微服务网关
微服务网关是所有外部请求的入口,主要功能有统一鉴权、限流、路由转发、负载均衡、日志记录、数据转换等。
Spring Cloud Gateway是Spring Cloud官方推出的网关框架。需要SpringBoot2.0版本以上支持。
核心概念
- 路由:网关最基本的功能,包含了ID、目标URI、断言集合以及过滤器集合
- 断言:定义匹配规则,可以定义匹配的路径、header信息、请求参数等
- 过滤器:也可称为拦截器,可以在每个请求服务之前、之后进行处理,典型的请求前处理有鉴权、限流。
其原理图如下:
二、Spring Gateway Demo应用
基于前一节的Nacos应用,新增了一个gateway-demo子模块,本例子通过gateway-demo调用nacos-demo中定义的sayHello接口。
pom.xml定义如下,这里引入了log4j2,注意这里不引入spring-boot-starter-web依赖。
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
application.yml配置如下,简单定义了一个路由。
server:
port: 9003
spring:
application:
name: gateway-demo
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes: # 路由配置
- id: nacos-service # id为nacos-service的路由配置
uri: lb://nacos-demo # 访问nacos上的nacos-demo服务,lb是load balance的缩写,代表负载均衡
filters:
- StripPrefix=2 # 定义截取的路径个数,比如网关访问路径/api/nacos/firstApi/sayHello,如果定义为2,则内部访问nacos-demo服务路径为/firstApi/sayHello
predicates:
- Path=/api/nacos/** # 网关路径定义,以/api/nacos开头的服务都访问nacos-demo服务
应用启动类代码片段如下。
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
三、测试网关
nacos-demo提供的接口为
通过网关调用如下地址
简单说明下跳转过程
- 访问/api/nacos/firstApi/sayHello,请求达到网关
- 网关匹配到路由规则nacos-service,通过路径是/api/nacos开头匹配
- 执行定义的过滤器 StripPrefix=2,这个意思是路由访问nacos-service服务的时候,访问路径截断两层,即由/api/nacos/firstApi/sayHello改为/firstApi/sayHello
- 最终请求访问达到nacos-demo应用,访问其/firstApi/sayHello接口
四、总结
没有理解网关的内容,导致在测试路由跳转的时候一直不成功,花费了较多时间。后面查询了资料才发现需要定义StripPrefix=2,对请求路径进行截断,才能正常路由。