标签: spring-cloud-gateway

Spring Cloud Gateway注入头

在GatewayFilter中,我尝试将标头注入到请求中,如下所示。

@Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //DO SOME AUTHORIZATION OPERATIONS String jwt = "xxxxx" exchange.getRequest().getHeaders().add("headerkey", jwt); return chain.filter(exchange); }

但是我收到以下错误:

java.lang.UnsupportedOperationException: null
at java.util.Collections$UnmodifiableMap.computeIfAbsent(Collections.java:1535) ~[na:1.8.0_111]
at org.springframework.http.HttpHeaders.add(HttpHeaders.java:1425) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at com.trimble.sample.springcloudgateway.filter.AuthGatewayFilter.filter(AuthGatewayFilter.java:30) ~[classes/:na]
at org.springframework.cloud.gateway.filter.OrderedGatewayFilter.filter(OrderedGatewayFilter.java:44) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
at org.springframework.cloud.gateway.handler.FilteringWebHandler$DefaultGatewayFilterChain.filter(FilteringWebHandler.java:103) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
at org.springframework.cloud.gateway.filter.NettyWriteResponseFilter.filter(NettyWriteResponseFilter.java:62) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
at org.springframework.cloud.gateway.handler.FilteringWebHandler$GatewayFilterAdapter.filter(FilteringWebHandler.java:121) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
at org.springframework.cloud.gateway.filter.OrderedGatewayFilter.filter(OrderedGatewayFilter.java:44) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
at org.springframework.cloud.gateway.handler.FilteringWebHandler$DefaultGatewayFilterChain.filter(FilteringWebHandler.java:103) ~[spring-cloud-gateway-core-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
Run Code Online (Sandbox Code Playgroud)

spring-cloud spring-cloud-gateway

3
推荐指数
2
解决办法
3054
查看次数

拒绝访问 Spring Cloud Gateway 路由的某一特定子路径

我们在后端服务前面使用 Spring Cloud Gateway。我们有一条类似于以下的路线:

  routes:
    - id: foobar-service
      uri: lb://foobar-service
      predicates:
        - Path=/foobar/**
      filters:
        - StripPrefix=1
Run Code Online (Sandbox Code Playgroud)

我们想要拒绝访问一个特定的子路径(例如/foobar/baz/**),但将其余子路径保持打开状态。是否可以使用 YAML 语法来执行此操作?也许我们需要使用 Fluent API 来实现路由?

spring-cloud spring-cloud-gateway

3
推荐指数
1
解决办法
2844
查看次数

Spring Cloud Kubernetes + Spring Cloud Gateway:无法找到 k8s 服务的实例

我正在使用 Spring Cloud Kubernetes + Spring Cloud Gateway(SCG),但在 GKE 上部署我的应用程序时遇到了一些麻烦。SCG 没有找到 k8s 服务,我仍然收到这个错误:

There was an unexpected error (type=Service Unavailable, status=503).
Unable to find instance for uiservice
Run Code Online (Sandbox Code Playgroud)

uiservice 是 Angular 应用程序。

当我看一看时,.../actuator/gateway/routes我得到了这个结果:

[
  {
    "route_id": "CompositeDiscoveryClient_gateway",
    "route_definition": {
      "id": "CompositeDiscoveryClient_gateway",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "pattern": "/gateway/**"
          }
        }
      ],
      "filters": [
        {
          "name": "RewritePath",
          "args": {
            "regexp": "/gateway/(?<remaining>.*)",
            "replacement": "/${remaining}"
          }
        }
      ],
      "uri": "lb://gateway",
      "order": 0
    },
    "order": 0
  },
  {
    "route_id": "CompositeDiscoveryClient_uiservice",
    "route_definition": …
Run Code Online (Sandbox Code Playgroud)

kubernetes spring-cloud spring-cloud-gateway spring-cloud-kubernetes

3
推荐指数
1
解决办法
2110
查看次数

在 Spring 云网关中使用 Resilience4j 为路由配置特定断路器

我尝试在我的 spring 云网关中配置 Resilience4j 没有成功。我发现的所有内容都是针对 Hystrix 或纯 Java 的。

我已经将网关配置为在我的服务上传输请求,没关系。

但是不可能在上面配置resilience4j。我在 R4J 的反应方面有一个很好的神器。

Spring Cloud API 和网关中 Resilience4j 的配置不同?

查看我的配置文件。

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: helloworld_service
          uri: "https://localhost:8080"
          predicates:
            - Path=/helloworld/**
          filters:
            - RewritePath=/helloworld/(?<segment>.*), /$\{segment}
            - name: CircuitBreaker
              args:
                name: helloworld
      httpclient:
        ssl:
          useInsecureTrustManager: true

# RESILIENCE4J PROPERTIES
resilience4j:
  circuitbreaker:
    configs:
      default:
        #registerHealthIndicator: true
        ringBufferSizeInClosedState: 10
        ringBufferSizeInHalfOpenState: 3
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenStateMillis: 2000
        failureRateThreshold: 50
        eventConsumerBufferSize: 10
    instances:
      helloworld:
        baseConfig: default
        ringBufferSizeInClosedState: 5
Run Code Online (Sandbox Code Playgroud)

我的依赖:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId> …
Run Code Online (Sandbox Code Playgroud)

spring-cloud-gateway resilience4j

3
推荐指数
1
解决办法
4002
查看次数

在 Spring Cloud Gateway 中将配置从 Ribbon 更改为 Spring Cloud Load Balancer

我有以下带有功能区的 Spring Cloud Gateway 配置

server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
        - id: UserModule
          uri: lb://load-balanced-service-user
          predicates:
            - Path=/api/user/**
ribbon:
  eureka:
    enabled: false
Load-balanced-service-user:
  ribbon:
    listOfServers: localhost:9999,localhost:8888
Run Code Online (Sandbox Code Playgroud)

现在我想删除 Ribbon 并替换为 Spring Cloud 负载均衡器。

我添加了

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

现在我需要在 application.yaml 文件中添加哪些其他配置才能切换到 Spring Cloud 负载均衡器?我想在 .yaml 文件上添加配置。我不想用 .yaml 文件中配置的功能区破坏旧结构。

spring-boot spring-cloud-netflix spring-cloud-gateway spring-cloud-loadbalancer

3
推荐指数
1
解决办法
3547
查看次数

Spring Cloud Gateway:在路径中使用查询参数值?

在Spring Cloud Gateway中,有没有办法获取查询参数的值并在目标路径中使用它?

例如

/inbound/path?someId=123
Run Code Online (Sandbox Code Playgroud)

导致调用

/outbound/123/detail
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

predicates:
  - Path=/inbound/path
  - Query=someId, (?<theId>/?.*)
filters:
  - SetPath=/outbound/{theId}/detail
Run Code Online (Sandbox Code Playgroud)
predicates:
  - Path=/inbound/path
  - Query=someId, {theId}
filters:
  - SetPath=/outbound/{theId}/detail
Run Code Online (Sandbox Code Playgroud)
predicates:
  - Path=/inbound/path
filters:
  - RewritePath=/inbound/path?someId=(?<theId>/?.*) /outbound/$\{theId}/detail
Run Code Online (Sandbox Code Playgroud)

spring-cloud-gateway

3
推荐指数
1
解决办法
7079
查看次数

Spring Cloud API Gateway 路由不起作用

我使用以下技术设计了一个微服务原型

  1. 尤里卡服务器(发现服务器)
  2. Spring boot(后端服务)
  3. Spring Cloud API 网关

上面提到的服务正在起床,ApI Gatewayback end servicesEureka服务器中注册

在此处输入图片说明

API 网关路由配置

server.port=8080
eureka.client.serviceUrl.defaultZone = http://localhost:8083/eureka
spring.application.name=ApiGateway
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true

spring.cloud.gateway.routes[0].id=service1
spring.cloud.gateway.routes[0].uri=lb://MICROSERVICE1
spring.cloud.gateway.routes[0].predicates[0]=Path=/service1/**
Run Code Online (Sandbox Code Playgroud)

微服务配置

server.port=8081
server.address=127.0.0.1
eureka.client.serviceUrl.defaultZone = http://localhost:8083/eureka
spring.application.name=MicroService1
error.whitelabel.enabled= false
Run Code Online (Sandbox Code Playgroud)

控制器

@RestController
@RequestMapping("/service1")
public class HomeController {
    @GetMapping("/message")
    public String hello() {
        return "response from micro service1";
    }

}
Run Code Online (Sandbox Code Playgroud)

当我向网关发送请求时,它显示以下错误

2020-12-16 22:26:09.770 ERROR 16700 --- [ctor-http-nio-3] a.w.r.e.AbstractErrorWebExceptionHandler : [d3334561-1]  500 Server Error for HTTP GET "/service1/message"

java.net.UnknownHostException: failed to resolve 'LAPTOP-KU56B6A8' …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-cloud-gateway

3
推荐指数
2
解决办法
5642
查看次数

带有 Spring 缓存和咖啡因的 Spring 云网关

我有一个 Spring Cloud 网关,它将 API 剩余请求转发到一些微服务。

我想缓存特定请求的响应。为此我写了这个过滤器

@Component
@Slf4j
public class CacheResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<CacheResponseGatewayFilterFactory.Config> {
   private final CacheManager cacheManager;

   public CacheResponseGatewayFilterFactory(CacheManager cacheManager) {
     super(CacheResponseGatewayFilterFactory.Config.class);
     this.cacheManager = cacheManager;
   }

   @Override
   public GatewayFilter apply(CacheResponseGatewayFilterFactory.Config config) {
     final var cache = cacheManager.getCache("MyCache");
     return (exchange, chain) -> {
        final var path = exchange.getRequest().getPath();
        if (nonNull(cache.get(path))) {
            log.info("Return cached response for request: {}", path);
            final var response = cache.get(path, ServerHttpResponse.class);
            final var mutatedExchange = exchange.mutate().response(response).build();
            return mutatedExchange.getResponse().setComplete();
        }

        return chain.filter(exchange).doOnSuccess(aVoid -> {
            cache.put(path, exchange.getResponse());
        }); …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-cache spring-cloud-gateway caffeine-cache

3
推荐指数
1
解决办法
5649
查看次数

如何在Spring Cloud Gateway过滤器中读取和修改请求正文?谁能帮我

我可以在下面的过滤器中读取请求参数。我想更改其中一个参数,该怎么做?我使用的是Spring Cloud 2020.0.0版本

@Component
public class ReadRequestBodyFilter extends AbstractGatewayFilterFactory<ReadRequestBodyFilter.Config>{

  public static class Config {}
  
  public ReadRequestBodyFilter() {
    super(Config.class);
  }

  @Override
  public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
      String cachedBodyAttribute = exchange.getAttribute("cachedRequestBodyObject");
      System.out.println("cachedBodyAttribute-->"+cachedBodyAttribute);
      return chain.filter(exchange);
  };
  }

}
Run Code Online (Sandbox Code Playgroud)

spring-cloud-gateway

3
推荐指数
1
解决办法
7941
查看次数

Spring Cloud API Gateway 自定义过滤对象上的 ClassCastException 到 Config

我试图通过以下资源spring-cloud-gateway-creating-custom-route-filters-abstractgatewayfilterfactory在 Spring Cloud API Gateway 中实现授权标头的自定义过滤器。

这是我的设置。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.myapp.config</groupId>
  <artifactId>MyAPIGateway</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>MyAPIGateway</name>
  <description>Spring Cloud API Gateway Server</description>
  <properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
  </properties>
  <dependencies>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.9.1</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
    </dependency>

    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-test</artifactId>
      <scope>test</scope> …
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-cloud-gateway

3
推荐指数
1
解决办法
3287
查看次数