1. 首页
  2. 软件开发
  3. JAVA
  4. spring.cloud.gateway.discovery.locator.enabled配置项分析

spring.cloud.gateway.discovery.locator.enabled配置项分析

  • 发布于 2024-08-10
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

spring.cloud.gateway.discovery.locator.enabled

该配置默认为 false,此配置不支持动态配置,修改后需要重启 gateway 生效。

开启了 spring.cloud.gateway.discovery.locator.enable=true 这项配置后,gateway 会为每个服务创建一个默认的路由规则,将以服务名开头的请求路径转发到对应的服务。

如果你在配置文件中添加了该服务的其他规则,则两个规则会同时存在,并且都会生效。

相当于为每个服务默认增加了如下配置

- id: authority-center
  uri: lb://authority-center
  predicates:
    - Path=/authority-center/**
  filters:
    - StripPrefix=1

示例 1

gateway 配置文件如下

server:
  port: 9001
    
spring:
  cloud:
    gateway:
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: true

微服务配置如下

server:
  port: 7000
  servlet:
    context-path: /center
 
spring:
  application:
    name: authority-center

访问 url:http://127.0.0.1:9001/authority-center/center/authority/token

这时候无需其他配置,通过网关可以访问到 authority-center 微服务的 / authority/token 接口

示例 2

spring:
  cloud:
    gateway:
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: true
      routes:
        - id: e-commerce-authority-center
          uri: lb://authority-center
          predicates:
            - Path=/center/**

微服务配置如下

server:
  port: 7000
  servlet:
    context-path: /center
 
spring:
  application:
    name: authority-center

访问 url-1:http://127.0.0.1:9001/center/authority/token

访问 url-2:http://127.0.0.1:9001/authority-center/authority/token

这时候访问 url-1、url-2 可以正常访问

spring.cloud.gateway.discovery.locator.lowerCaseServiceId

该配置是针对自动生成路由的配置,

即 spring.cloud.gateway.discovery.locator.enabled=true 时自动生成的路由配置有效,对于手动配置的路由不生效

比如服务名配置为 AUTHORITY-CENTER 大写的服服务名,如果想访问到,需要使用如下路径

http://127.0.0.1:9001/AUTHORITY-CENTER/center/authority/token

如果配置了

spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true, 则可以使用如下的方式访问

http://127.0.0.1:9001/authority-center/center/authority/token