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
相关推荐
广州中轴线6 小时前
OpenStack on Kubernetes 生产部署实战(十三)
容器·kubernetes·openstack
晚霞的不甘6 小时前
Flutter for OpenHarmony天气卡片应用:用枚举与动画打造沉浸式多城市天气浏览体验
前端·flutter·云原生·前端框架
Tadas-Gao6 小时前
TCP粘包现象的深度解析:从协议本质到工程实践
网络·网络协议·云原生·架构·tcp
切糕师学AI7 小时前
Helm Chart 是什么?
云原生·kubernetes·helm chart
陈桴浮海8 小时前
【Linux&Ansible】学习笔记合集三
linux·运维·云原生·ansible
广州中轴线8 小时前
OpenStack on Kubernetes 生产部署实战(十七)
容器·kubernetes·openstack
研究司马懿10 小时前
【云原生】Gateway API高级功能
云原生·go·gateway·k8s·gateway api
陈桴浮海1 天前
Kustomize实战:从0到1实现K8s多环境配置管理与资源部署
云原生·容器·kubernetes
张小凡vip1 天前
Kubernetes--k8s中部署redis数据库服务
redis·kubernetes
Hello.Reader1 天前
Flink Kubernetes HA(高可用)实战原理、前置条件、配置项与数据保留机制
贪心算法·flink·kubernetes