我正在尝试使用Spring Cloud Gateway来路由我的微服务,但是即使微服务正常工作,网关路由也会返回空响应。我的微服务是一个简单的应用程序,它运行在端口5861
上。在经过特定路径的路由试验后,我通过预测所有情况来确保它路由,从而简单地将我的网关路由到它。
这是我的网关配置文件:
spring:
cloud:
gateway:
routes:
- id: product_service
uri: localhost:5861/
predicates:
- Path=/product-service/**
运行两个服务并击中它们后,我的微服务返回正确的响应:
$ curl -v http://localhost:5861/product/
* Trying 127.0.0.1:5861...
* Connected to localhost (127.0.0.1) port 5861 (#0)
> GET /product/ HTTP/1.1
> Host: localhost:5861
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Wed, 01 Jun 2022 19:41:40 GMT
<
* Connection #0 to host localhost left intact
[{"id":1,"name":"Apple","price":2},{"id":2,"name":"Apple","price":2},{"id":3,"name":"Apple","price":2}]
但是如果我尝试从我的API网关执行此操作,它不会返回任何内容,如果我尝试从浏览器访问它,则会出现空白页面。
$ curl -v http://localhost:5860/product-service/product
* Trying 127.0.0.1:5860...
* Connected to localhost (127.0.0.1) port 5860 (#0)
> GET /product-service/product HTTP/1.1
> Host: localhost:5860
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< content-length: 0
<
* Connection #0 to host localhost left intact
有人可以帮助我什么我错过了?我想从网关得到相同的响应。
看起来您的应用程序暴露了/product/
端点。从网关,您正在尝试从/product-service/product
重定向到服务的/product/
。默认情况下,spring云网关按原样重定向到uri。所以目前,我认为http://localhost:5860/product-service/product
被重定向到http://localhost:5861/product-service/product
。
如果需要从product-service的product-service/**
重定向到/**
,则使用RewritePath
过滤器。
下面是一个可能对你有用的用法示例:
spring:
cloud:
gateway:
routes:
- id: product_service
uri: localhost:5861/
predicates:
- Path=/product-service/**
filters:
- RewritePath=/product-service/(?<segment>/?.*),${segment}
工作更新:
spring:
cloud:
gateway:
routes:
- id: product_service
uri: http://localhost:5861/
predicates:
- Path=/product