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

Spring Cloud Gateway通常使用注册中心作为服务发现,但在Kubernetes里面,由于K8S已经集成了服务注册与发现功能,不必要再另外使用注册中心了,而且,还可以使用K8S的服务监控对服务进行监控。
本来按照网上教程,升级到最新版的springboot3.x,结果发现无法发现服务。后来按着官方指引,终于成功了,现分享给出来。

引进必要的依赖

    <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>

主程序

@SpringBootApplication
@EnableDiscoveryClient
public class IRMPGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(IRMPGatewayApplication.class, args);
    }
}

配置

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

相关推荐

  1. 原生周刊:K8s 中服务和网络 | 2024.4.29

    2024-04-04 05:06:02       49 阅读
  2. k8s 服务发现

    2024-04-04 05:06:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-04 05:06:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-04 05:06:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-04 05:06:02       82 阅读
  4. Python语言-面向对象

    2024-04-04 05:06:02       91 阅读

热门阅读

  1. 使用Docker 部署jenkins 实现自动化部署

    2024-04-04 05:06:02       36 阅读
  2. 【RAG】内部外挂知识库搭建-本地GPT

    2024-04-04 05:06:02       37 阅读
  3. 使用Linux strace追踪系统调用: 一个详细指南

    2024-04-04 05:06:02       37 阅读
  4. S3存储请求结果403错误

    2024-04-04 05:06:02       40 阅读