本博客源码可在Gitee下载。
书接上回,我在Spring Cloud 1和Spring Cloud 2中分别搭建了Eureka注册中心和客户端程序,并实现以客户端作为微服务在注册中心注册。接下来整个项目需要一个统一的入口来访问不同的微服务,就是本节中用到的spring gateway。
首先参照Spring Cloud 2搭建另一个客户端程序,端口设为9101,这里不再累述。 接下来搭建gateway网关:
build.gradle:
plugins {
id 'java'
id 'io.spring.dependency-management' version '1.1.6'
id 'org.springframework.boot' version '3.2.6'
}
group = 'cn.beeson'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
ext {
set('springCloudVersion', "2023.0.2")
}
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
# 服务发现配置,动态路由
discovery:
locator:
enabled: true
eureka:
client:
serviceUrl:
defaultZone: http://admin:123456@localhost:9000/eureka/
分别运行Eureka-Server,两个client程序,gateway网关程序,访问注册中心localhost:9000,界面如下,可以在注册中心看到两个客户端和网关程序:
接下来通过路由分别访问两个客户端程序:
eureka-client-demo的真实地址是localhost:9100/index,路由地址是localhost:9001/EUREKA-CLIENT-DEMO/index;
eureka-client-demo2的真实地址是localhost:9101/index,路由地址是localhost:9001/EUREKA-CLIENT-DEMO2/index。