让spring gateway 支持contextPath

2022-07-07 09:39:46

让spring gateway 支持contextPath

 1. 需求


    公司环境中把服务部署到了k8s中,通过对服务进行健康检测自动自动重启故障服务;
    所有服务都采用了 actuator/health

    因为spring gateway是采用webflux,无法通过server.servlet.contextPath来配置(业务服务都统一进行了配置)
    业务服务的访问路径: http://ip:8080/user/actuator/health
    网关的访问路径:      http://ip:8080/actuator/health
    业务服务路径带了contextPath,而网关的没有
    导致检测脚本可能需要额外的进行判断,不是很友好。
    需要想办法将网关与业务的路径调整到一致。


2. 问题


   为了解决这个问题,有两种思路:
    1. 所有业务服务不再配置 contextPath

    2. 让网关支持contextPath
    ---
    写这篇文章肯定是选择2了。
    因为我们的业务服务比较多,而且还有已经稳定运行使用的服务,所以无法简单的调整。


3. 解决


   使用的版本如下:
   spring-cloud-gateway:2.1.2
   spring-boot : 2.1.6
   ---
 题外话: 好像spring-boot 2.3 已经支持webflux设置contextPath了。

   思路:
网关本身没有contextPath,可以通过在路由中增加一条本地路由,通过自己转发自己,达到能处理contextPath

   配置:

spring:
  cloud:
    gateway:
      routes:
      # 网关本身没有contextPath,通过自己转发自己,达到能处理contextPath
      - id: self
        uri: http://localhost:${server.port}
        predicates:
        - Path=/${spring.application.name}/**
        filters:
        - StripPrefix=1
        order: -11000


  • 作者:xiaolaoban212
  • 原文链接:https://blog.csdn.net/xiaolaoban212/article/details/107224736
    更新时间:2022-07-07 09:39:46