- SpringCloud 2020.0.4 系列之 Gateway
- SpringCloud 2020.0.4 系列之Eureka
- SpringCloud 2020.0.4 系列之 Bus
- SpringCloud 2020.0.4 系列之 Stream
- SpringCloud 2020.0.4 系列之 Config
- SpringCloud 2020.0.4 系列之 Sleuth
- SpringCloud 2020.0.4 系列之 Feign
- SpringCloud 2020.0.4 系列之 Stream
- SpringCloud 2020.0.4 系列之 Stream
- SpringCloud 2020.0.4 系列之Hystrix看
1. 概述
老话说的好:做人要有幽默感,懂得幽默的人才会活的更开心。
言归正传,今天我们来聊聊 SpringCloud 的网关组件 Gateway,之前我们去访问 SpringCloud 不同服务的接口,都要去找每个服务的 IP地址 和 端口,有了 Gateway 这个组件,我们就可以从一个入口,去访问所有在 Eureka 中注册的服务。
闲话不多说,直接上代码。
2. Gateway 工程的搭建
2.1 主要依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
2.2 application.yml 主要配置
server:
port: 44000
spring:
application:
name: my-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
eureka:
client:
service-url:
defaultZone: http://zhuifengren1:35000/eureka/,http://zhuifengren2:35001/eureka/ # Eureka Server的地址
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
2.3 启动类注解
@SpringBootApplication
@EnableDiscoveryClient
public class MyGateWayApplication {
public static void main(String[] args) {
SpringApplication.run(MyGateWayApplication.class, args);
}
}
2.4 启动 Gateway 服务,并访问测试
1)启动 Eureka 服务
2)启动之前章节中讲到的 my-eureka-client 服务
3)启动 Gateway 服务
4)通过 Gateway 服务调用 my-eureka-client 服务暴露的接口
接口地址:http://localhost:44000/MY-EUREKA-CLIENT/eurekaClient/hello
地址格式:http://Gateway服务IP:端口/服务名大写/请求路径
2.5 地址中服务名改为小写
刚刚的实验中,我们发现,通过 Gateway 访问服务接口,服务的名称必须写为大写,才能正确访问接口,有点不习惯,我们可以通过配置将其统一改为小写。
增加如下配置即可:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true # service-id 是否用小写
3. 自定义动态路由
3.1 概述
有时我们不想用服务名当做接口的前缀,可以自定义动态路由。
3.2 增加动态路由
POST http://localhost:44000/actuator/gateway/routes/myroute
最后的 myroute 是自定义路由的 ID,保证唯一即可。
参数:
{
"predicates": [
{
"name":"Path",
"args":{
"_genkey_0":"/myroute/**"
}
}
],
"filters": [
{
"name":"StripPrefix",
"args":{
"_genkey_0":"1"
}
}
],
"uri": "lb://MY-EUREKA-CLIENT",
"order": 0
}
参数的含义是,所有以 myroute 开头的URL,统一转发到 MY-EUREKA-CLIENT 服务。
3.3 使用动态路由访问接口
http://localhost:44000/myroute/eurekaClient/hello
3.4 删除动态路由
DELETE http://localhost:44000/actuator/gateway/routes/myroute
4. 综述
今天聊了一下 SpringCloud 的 Gateway 组件,希望可以对大家的工作有所帮助。
欢迎帮忙点赞、评论、转发、加关注 :)
关注追风人聊Java,每天更新Java干货。
网友评论