书接上回,我在Cloud(1)和Cloud(2)中分别搭建了Eureka注册中心和客户端程序,并实现以客户端作为微服务在注册中心注册。接下来整个项目需要一个统一的入口来访问不同的微服务,就是本节中用到的spring gateway。
首先参照Cloud(2)搭建另一个客户端程序,端口设为9101,这里不再累述。
接下来搭建gateway网关:
build.gradle:
plugins {
id 'java'
id 'io.spring.dependency-management' version '1.1.0'
id 'org.springframework.boot' version '2.6.14'
}
group = 'cn.beeson'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
ext {
set('springCloudVersion', "2021.0.6")
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}
application.yml:
server:
port: 9001
#服务名
spring:
application:
name: gateway-service
cloud:
gateway:
filter:
remove-non-proxy-headers:
headers:
- dummy
# 路由配置
routes:
- id: demo1
# 微服务的spring.application.name属性,或者其他非spring服务在注册中心中的name
uri: lb://eureka-client-demo
# 转发路径
predicates:
- Path=/demo1/**
# 服务的实际路径是lb://eureka-client-demo/index
# 但是通过网关转发的路径是lb://eureka-client-demo/demo1/index
# 因此需要去掉1级路径,即StripPrefix=1
# 如果想要在服务实际路径前追加路径,使用- PrefixPath
filters:
- StripPrefix=1
- id: demo2
uri: lb://eureka-client-demo2
predicates:
- Path=/demo2/**
filters:
- StripPrefix=1
eureka:
client:
serviceUrl:
defaultZone: http://admin:123456@localhost:9000/eureka/
分别运行Eureka-Server,两个client程序,gateway网关程序,访问注册中心localhost:9000,界面如下,可以在注册中心看到两个客户端和网关程序:

注册中心
接下来通过路由分别访问两个客户端程序,
eureka-client-demo的真实地址是localhost:9100/index,路由地址是localhost:9001/demo1/index;
eureka-client-demo2的真实地址是localhost:9101/index,路由地址是localhost:9001/demo2/index。

通过gateway访问demo1

通过gateway访问demo2