springcloud gateway设置context-path的操作

今天说一下遇到的问题,关于 springcloud gateway 设置 context-path 的问题。

1.使用场景

由于没有申请二级域名,网关使用的地址是 xxx.com/gateway/ 用nginx转发的时候 /gateway/ 也被用来寻址。

gateway 没办法设置 context-path ,针对我这个场景有3个解决方案。

2.解决方案

2.1 增加本地路由(有一个网址指向自己,这里就是 /gateway)

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

这种方式会丢失请求,暂时没考虑原因,就pass了。

2.2 增加过滤器,改写路径

ApiFilter.java

package com.yiche.ballast.filter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono; 

@Configuration
public class ApiFilter {
    @Value("${spring.cloud.gateway.api-prefix:/gateway}")
    private String prefix;
    @Bean
    @Order(-1)
    public WebFilter apiPrefixFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            String path = request.getURI().getRawPath();
            if (!path.contains(prefix)) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.BAD_GATEWAY);

                DataBuffer buffer = response
                        .bufferFactory()
                        .wrap(HttpStatus.BAD_GATEWAY.getReasonPhrase().getBytes());
                return response.writeWith(Mono.just(buffer));
            }
            String newPath = path.replaceFirst(prefix, "");
            ServerHttpRequest newRequest = request.mutate().path(newPath).build();

            return chain.filter(exchange.mutate().request(newRequest).build());
        };
    }
}

这样/gateway 请求进来之后,转发到routers 的时候会把 /gateway去掉,缺点是每个请求进来都需要对路径处理一次。

能配置的尽量不写代码。

2.3 修改配置,在所有的router路径前加前缀(这里就是都加上 /gateway)

spring:
    cloud:
        gateway:
            routes:
            - id: api-route
              filters:
                - StripPrefix=1
              predicates:
                - name: Path
                  args[pattern]: /gateway/api/**
              uri: lb://xxx-api

偷懒的做法,路由多的时候也挺难受。

现在路由不多,选择了第三种方式。看各自的场景选择吧。

springcloud 的gateway踩坑

添加了路由规则的配置以后,SpringCloud无法正常启动,启动的时候报错

1、配置文件中开启debug=true模式

错误信息显示缺少javax.validation.ValidatorException类;

2、在pom文件中添加hibernate-validator(以及所有相关依赖)

3、结果仍旧报错,此时错误信息:

不能为空,之前是配置在yml文件中,后来换成了properties,问题就解决了;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Springcloud GateWay网关配置过程图解

    一般为了不暴露自己的端口信息等,会选择架构一个网关在前面进行阻挡,起到保护的作用.附上一张工作示列图. 1.配置网关9527 gateway作为网关需要和其他的应用一样需要注册进eureka中进行管理,先创建应用gateway9527 pom文件,关键是gateway依赖 <dependencies> <dependency> <groupId>com.bai</groupId> <artifactId>cloud-api-common</

  • spring cloud gateway 如何修改请求路径Path

    一.背景 项目升级改造,老项目使用请求url中特定参数进行服务路由,现使用gateway网关进行路由服务信息 二.根据参数信息修改请求路径Path @Component public class RequestFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpR

  • 解决spring cloud gateway 获取body内容并修改的问题

    之前写过一篇文章,如何获取body的内容. Spring Cloud Gateway获取body内容,不影响GET请求 确实能够获取所有body的内容了,不过今天终端同学调试接口的时候和我说,遇到了400的问题,报错是这样的HTTP method names must be tokens,搜了一下,都是说https引起的.可我的项目还没用https,排除了. 想到是不是因为修改了body内容导致的问题,试着不修改body的内容,直接传给微服务,果然没有报错了. 问题找到,那就好办了,肯定是我新构

  • SpringCloud Gateway 路由配置定位原理分析

    环境:springcloud Hoxton.SR11 本节主要了解系统中的谓词与配置的路由信息是如何进行初始化关联生成路由对象的.每个谓词工厂中的Config对象又是如何被解析配置的. 所有的谓词工厂中的Config中属性值是如何被配置的. 在SpringCloud Gateway中的所有谓词工厂如下: 命名规则:XxxRoutePredicateFactory.所有的这些谓词工厂都是如下的继承关系 public class MethodRoutePredicateFactory extends

  • springcloud gateway设置context-path的操作

    今天说一下遇到的问题,关于 springcloud gateway 设置 context-path 的问题. 1.使用场景 由于没有申请二级域名,网关使用的地址是 xxx.com/gateway/ 用nginx转发的时候 /gateway/ 也被用来寻址. gateway 没办法设置 context-path ,针对我这个场景有3个解决方案. 2.解决方案 2.1 增加本地路由(有一个网址指向自己,这里就是 /gateway) spring: cloud: gateway: routes: #

  • Web应用中设置Context Path案例详解

    URL:http://hostname.com/contextPath/servletPath/pathInfo Jetty 如果没有contextPath,则默认使用root上下文,root上下文的路径为"/". warName.war 在没有XML IoC文件的情况下: 如果WAR文件名是myapp.war,那么上下文路径是:/myapp: 如果WAR文件名是ROOT.war,那么上下文路径是:/: 如果WAR文件名是ROOT-foobar.war,那么上下文路径是/,虚拟host

  • SpringCloud gateway跨域配置的操作

    gateway跨域配置 gateway允许跨域的配置和zuul的不一样,记录一下. 版本 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!--

  • SpringCloud Gateway跨域配置代码实例

    这篇文章主要介绍了SpringCloud Gateway跨域配置代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Springboot版本:2.1.8.RELEASE SpringCloud版本:Greenwich.SR2 yml配置: spring: cloud: gateway: globalcors: cors-configurations: '[/**]': # 允许携带认证信息 # 允许跨域的源(网站域名/ip),设置*为全部

  • 详解SpringCloud Gateway 2020.0.2最新版

    简述 官网:https://spring.io/projects/spring-cloud-gateway GitHub地址:https://github.com/spring-cloud/spring-cloud-gateway 本文编写自2021年4月7日,当前SpringCloud最新版本为2020.0.2版本 本文使用版本为 SpringCloud 版本2020.0.2 spring-cloud-starter-gateway版本3.0.2 spring-boot-starter版本2.

  • SpringCloud Gateway读取Request Body方式

    目录 Gateway读取RequestBody 分析ReadBodyPredicateFactory 配置ReadBodyPredicateFactory 编写自定义GatewayFilterFactory 完整的yml配置 Gateway自定义filter获取body的数据为空 首先创建一个全局过滤器把body中的数据缓存起来 在自定义的过滤器中尝试获取body中的数据 解析body的工具类 Gateway读取Request Body 我们使用SpringCloud Gateway做微服务网关

  • SpringCloud Gateway使用redis实现动态路由的方法

    1. 将 actuator 端点暴露出来 management: endpoints: web: exposure: include: "*" 2. redis 配置 https://www.jb51.net/article/203766.htm 3. 将原内存路由持久化到 redis @Component public class RedisRouteDefinitionRepository implements RouteDefinitionRepository { /** * h

  • SpringCloud gateway如何修改返回数据

    版本说明 开源软件 版本 springboot 2.1.6.RELEASE jdk 11.0.3 gradle 主要引入了springboot 2.1,lombok plugins { id 'org.springframework.boot' version '2.1.6.RELEASE' id 'java' id "io.freefair.lombok" version "3.6.6" }apply plugin: 'io.spring.dependency-m

  • 浅谈springcloud gateway 连接保活问题

    项目中使用了springcloud gateway作为网关,上游与负载均衡服务器连接. 近期通过监控系统观察,发现网关与上游负载均衡服务器保持的TCP连接有300+,初步怀疑是调用方未释放连接 用如下方法进行分析: 1)周期性采集当前建立的连接及端口数据 首先是每隔10分钟连续采集2两个小时,发现在两个小时之内新出现的端口不到12个,再逐步缩短采样周期,到最后每秒采集一次,分析发现每秒种建立一个连接,同时关闭一个连接,当仍存在300+连接,这些连接对应的端口称为不活跃端口,记录下这300+不活跃

随机推荐