如何在 spring webflux 中重定向请求?

How to redirect a request in spring webflux?

如何在 spring WebFlux 中创建重定向 rest Web 服务? WebFlux 好像还没有重定向功能!

我想要这样的东西:

 @Bean
RouterFunction<ServerResponse> monoRouterFunction() {
    return 
        route(GET("/redirect/{id}"),{
            req -> req.Redirect( fetchAUrlFromDataBase() )
        })
@Bean
RouterFunction<ServerResponse> routerFunction() {
     route(GET("/redirect"), { req ->
          ServerResponse.temporaryRedirect(URI.create(TargetUrl))
                    .build()
        }
    })

}

非常感谢 Johan Magnusson

您可以在 Spring boot main class 中添加以下代码以将“/”请求重定向到“/login”页面。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;   

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    @Bean
    RouterFunction<ServerResponse> routerFunction() {
        return  route(GET("/"), req ->
                ServerResponse.temporaryRedirect(URI.create("/login"))
                        .build());
    }
}

我使用下面的代码片段设法实现了这一点。 我将重定向字符串传递给渲染函数。

下面的代码重定向到登录路由。

ServerResponse.ok().render("redirect:/login")