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
相关推荐
Hernon23 分钟前
微服务架构设计 - 架构取舍决策CAP
微服务·云原生·架构
你才是臭弟弟1 小时前
Amazon S3 和 MinIO (数据湖的选型)
大数据·云原生
Gold Steps.1 小时前
MySQL Operator for Kubernetes自动实现整个生命周期
mysql·云原生·kubernetes
NGINX开源社区3 小时前
借助 Okta 和 NGINX Ingress Controller 实现 K8s OpenID Connect 身份验证
运维·nginx·kubernetes
阿里云云原生4 小时前
RUM 链路打通实战:打破移动端可观测性黑洞
阿里云·云原生·rum
久绊A5 小时前
K8s集群异常Pod高效排查命令(kube-system核心场景)
云原生·容器·kubernetes
小二·5 小时前
Go 语言系统编程与云原生开发实战(第3篇):企业级 RESTful API 开发 —— 中间件、验证、文档与权限控制
云原生·golang·restful
虫小宝6 小时前
从单体到微服务:淘客返利系统的演进路径与拆分边界划分原则
微服务·云原生·架构
噎住佩奇6 小时前
k8s-控制器
容器·kubernetes
ProgrammerPulse7 小时前
K8s 运维告别 “猜谜游戏”:青云云易捷v6.0对接 K8sGPT,AI 赋能一键解锁智能诊断
云原生