Spring Cloud Gateway通常使用注册中心作为服务发现,但在Kubernetes里面,由于K8S已经集成了服务注册与发现功能,不必要再另外使用注册中心了,而且,还可以使用K8S的服务监控对服务进行监控。
本来按照网上教程,升级到最新版的springboot3.x,结果发现无法发现服务。后来按着官方指引,终于成功了,现分享给出来。
引进必要的依赖
xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-fabric8</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-fabric8-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
主程序
java
@SpringBootApplication
@EnableDiscoveryClient
public class IRMPGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(IRMPGatewayApplication.class, args);
}
}
配置
yaml
spring:
cloud:
gateway:
routes:
- id: base-service-route # 路由的id,要保证其唯一性
uri: lb://irmp-base-service # lb 表示 从nacos 中按照名称获取微服务,并遵循负载均衡策略, report-service 即微服务注册名
predicates:
- Path=/base/v2/** # 使用断言
filters:
# - StripPrefix=1 # 去掉路径前n个前缀
discovery:
locator:
enabled: true
lower-case-service-id: true
kubernetes:
loadbalancer:
mode: SERVICE
logging:
level:
org.springframework.cloud.gateway: trace