我能够将 Spring Cloud Gateway 与 Springdoc OpenAPI 集成到一个具有面向微服务架构的小型应用程序中。但现在,当我打开 Swagger UI 来测试控制器 (StudentController) 的端点时,我意识到控制器根级别的 @RequestMapping 不包含在要测试的端点的 URL 中。
路由定义如下:
routes:
- id: students-service
uri: lb://STUDENTS-SERVICE
predicates:
- Path=/students/**
filters:
- RewritePath=/students/(?<path>.*), /$\{path}
- id: openapi
uri: http://localhost:${server.port}
predicates:
- Path=/v3/api-docs/**
filters:
- RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/v3/api-docs
StudentController 如下:
@RestController
@RequestMapping("/api/v1")
@Tag(name = "Students")
public class StudentQueryController {
@GetMapping("/message")
public String dummyGet() {
return "Student Service Dummy GET";
}
}
在 Swagger UI 中,我希望获得类似“http://localhost:8060/students/api/v1/message”的 URL,但我得到的是“http://localhost:8060/api/v1/message”。
有人愿意帮助我解决这个问题吗?
提前致谢。
如果您在 Spring Cloud Gateway 等代理后面的应用程序中配置了 springdoc,则应该在服务应用程序中配置此属性:
server.forward-headers-strategy=framework
该属性是在 spring-boot 2.2.0 中引入的。
解释:
当请求通过 Spring Cloud Gateway 时,一些与代理相关的标头将被添加到请求中(例如x-forwarded-host
, x-forwarded-proto
, etc).
设置此属性后,您的应用程序将使用这些标头进行正确的重定向。而不是重定向到/api/v1/message
它将重定向到/students/api/v1/message
(自从/students
前缀将在x-forwarded-prefix
标题)。
仅当所有应用程序背后的代理正确配置了这些标头并且您可以信任此代理时,才使用此设置。
如果您限制所有应用程序只能通过 Spring Cloud Gateway 访问,那就没问题了。
您可以阅读有关此参数和行为的更多信息here https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.webserver.use-behind-a-proxy-server.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)