如何在Spring Webflux中获取当前控制器方法的URL?

这个问题类似于在Spring MVC中获取当前URL的最佳方法是什么?但对于Webflux(它也可能与如何在spring-webflux中获取当前请求的上下文有关,但这个问题更具体,所以我希望有一个解决方案)。

我想做的是在Webflux控制器中获取当前URL。例如:

@GetMapping("/greeting")

public Mono<Greeting> greeting() {

   String linkToCurrentResource = .. // How do I get this?

   Greeting greeting = new Greeting("hello",  linkToCurrentResource);

   return Mono.just(greeting);

}

如果运行在负载均衡器后面,最好应了解标头。因此,在这种情况下,我想成为类似.如果这很重要,我正在使用Netty服务器实现。linkToCurrentResourceX-Forwarded-???linkToCurrentResourcehttps://external-uri.com/api/greeting


梵蒂冈之花
浏览 219回答 1
1回答

蝴蝶不菲

您可以使用 ServerHttpRequest 作为方法参数来获取 :uri@RestControllerpublic class GreetingController {&nbsp; @GetMapping("/greeting")&nbsp; public Mono<Greeting> getGreeting(ServerHttpRequest serverHttpRequest) {&nbsp; &nbsp; return Mono.just(new Greeting("greeting", serverHttpRequest.getURI().toString()));&nbsp; }}如果运行在负载均衡器后面,最好应了解标头。linkToCurrentResourceX-Forwarded-???然后,您可以公开转发标题变压器。@Bean从其文档中:从 “” 和 “” 标头中提取值以覆盖请求(即 ),以便它反映客户端发起的协议和地址。ForwardedX-Forwarded-*URIHttpRequest.getURI()@Configurationopen class MvcConfig {&nbsp; &nbsp; @Bean&nbsp; &nbsp; open fun forwardedHeaderTransformer() = ForwardedHeaderTransformer()}以下是一些测试:@ExtendWith(SpringExtension::class)@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,&nbsp; &nbsp; &nbsp; &nbsp; properties = ["server.port=4333"])class GreetingController2Test {&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private lateinit var restTemplate: TestRestTemplate&nbsp; &nbsp; @Test&nbsp; &nbsp; fun `should return uri`() {&nbsp; &nbsp; &nbsp; &nbsp; val responseEntity = restTemplate.getForEntity("/greeting", Greeting::class.java)&nbsp; &nbsp; &nbsp; &nbsp; val greeting = responseEntity.body!!&nbsp; &nbsp; &nbsp; &nbsp; assertEquals("http://localhost:4333/greeting", greeting.uri)&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; fun `should return uri composed from forwarded-??? headers`() {&nbsp; &nbsp; &nbsp; &nbsp; val headers = HttpHeaders()&nbsp; &nbsp; &nbsp; &nbsp; headers["X-Forwarded-Host"] = "external-uri.com"&nbsp; &nbsp; &nbsp; &nbsp; headers["X-Forwarded-Proto"] = "https"&nbsp; &nbsp; &nbsp; &nbsp; headers["X-Forwarded-Prefix"] = "/prefix"&nbsp; &nbsp; &nbsp; &nbsp; val httpEntity = HttpEntity(null, headers)&nbsp; &nbsp; &nbsp; &nbsp; val responseEntity = restTemplate.exchange("/greeting", HttpMethod.GET, httpEntity, Greeting::class.java)&nbsp; &nbsp; &nbsp; &nbsp; val greeting = responseEntity.body!!&nbsp; &nbsp; &nbsp; &nbsp; assertEquals("https://external-uri.com/prefix/greeting", greeting.uri)&nbsp; &nbsp; }}和 :Greeting.ktdata class Greeting(&nbsp; &nbsp; &nbsp; &nbsp; val g: String? = null,&nbsp; &nbsp; &nbsp; &nbsp; val uri: String? = null)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java