Spring Cloud Gateway使用K8S (Kubernetes)的云原生服务发现

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
相关推荐
pp-周子晗(努力赶上课程进度版)11 小时前
Docker、Kubernetes与AWS中控机是什么?
docker·容器·kubernetes·aws
不爱笑的良田16 小时前
从零开始的云原生之旅(十一):压测实战:验证弹性伸缩效果
云原生·容器·kubernetes·go·压力测试·k6
Wang's Blog21 小时前
Nestjs框架: 微服务容器化部署与网络通信解决方案
docker·微服务·云原生·架构·nestjs
Serverless社区1 天前
为什么别人用 DevPod 秒启 DeepSeek-OCR,你还在装环境?
阿里云·云原生·serverless
一枚正在学习的小白1 天前
k8s的包管理工具helm3--流程控制语句和变量(3)
linux·运维·服务器·云原生·kubernetes
缘的猿1 天前
kubectl 学习心得:从入门到实践的 K8s 命令行掌控之旅
云原生·容器·kubernetes
阿里云云原生1 天前
用户说“App 卡死了”,你却查不到原因?可能是监控方式错了
云原生
2401_840192271 天前
什么是ingress?
docker·容器·kubernetes
落日漫游1 天前
ArgoCD与Helm:云原生部署对比解析
java·容器·kubernetes