一、添加 Spring Cloud Gateway 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
二、配置网关路由
在application.yaml中配置如下内容:
spring:
cloud:
gateway:
routes:
- id: service1_route
uri: http://localhost:8081
predicates:
- Path=/service1/**
- id: service2_route
uri: http://localhost:8082
predicates:
- Path=/service2/**
在上面的示例中,配置了两个网关路由,分别将请求路由到 http://localhost:8081 和 http://localhost:8082。其中,id 属性表示路由的唯一标识符,uri 属性表示路由的目标地址,predicates 属性表示路由的匹配规则。
使用了 Path=/service1/** 和 Path=/service2/** 作为路由的匹配规则,表示当客户端发送的请求路径以 /service1 或 /service2 开头时,网关会将请求路由到对应的服务地址。
三、配置网关端口和其他属性
server:
port: 8888
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: service1_route
uri: lb://service1
predicates:
- Path=/service1/**
- id: service2_route
uri: lb://service2
predicates:
- Path=/service2/**
在上面的示例中,配置了网关的端口为 8888,并启用了服务发现功能,这样网关就可以自动发现并路由到注册在服务注册中心中的微服务。将 uri 属性的值设置为 lb://service1 和 lb://service2,表示使用负载均衡的方式将请求路由到多个服务实例中。
四、uri: http://localhost:8081和uri: lb://service1的区别
- 使用uri: http://localhost:8081
在网关配置中,可以使用目标服务的 URL 地址作为路由的目标地址,例如 http://localhost:8081。但是,这种方式有一个缺点:如果服务有多个实例,需要手动指定其中一个实例的地址,这样就无法实现负载均衡的功能。 - 使用uri: lb://service1
为了解决这个问题,可以使用服务发现功能来自动获取服务的实例地址,并实现负载均衡的功能。在 Spring Cloud 中,使用 Ribbon 或 Spring Cloud LoadBalancer 来实现这个功能。在配置网关路由时,使用 lb:// 前缀来代替具体的服务实例地址,例如 lb://service1。这样,网关就会自动从服务注册中心中获取服务的实例地址,并实现负载均衡的功能。
使用 lb:// 前缀的方式还可以支持服务的动态添加和删除。当新的服务实例注册到服务注册中心中时,网关会自动更新路由配置,从而将请求路由到新的服务实例中。同样地,当服务实例下线时,网关也会自动将其从路由配置中删除,以保证请求不会再被路由到已下线的服务实例中。