@Slf4j
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
log.info("react result is {}",welcomeWebClient.getResult());
}
}
编程方式使用webFlux
刚刚的注解方式其实跟我们常用的Spring MVC基本上是一样的。
接下来,我们看一下,如果是以编程的方式来编写上面的逻辑应该怎么处理。
首先,我们定义一个处理hello请求的处理器:
@Component
public class WelcomeHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("www.flydean.com!"));
}
}
和普通的处理一样,我们需要返回一个Mono对象。
注意,这里是ServerRequest,因为WebFlux中没有Servlet。
有了处理器,我们需要写一个Router来配置路由:
@Configuration
public class WelcomeRouter {
@Bean
public RouterFunction<ServerResponse> route(WelcomeHandler welcomeHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello").
and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), welcomeHandler::hello);
}
}
上面的代码将/hello和welcomeHandler::hello进行了绑定。
WelcomeWebClient和Application是和第一种方式是一样的。
public class WelcomeWebClient {
private WebClient client = WebClient.create("http://localhost:8080");
private Mono<ClientResponse> result = client.get()
.uri("/hello")
.accept(MediaType.TEXT_PLAIN)
.exchange();
public String getResult() {
return " result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
}
}
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
log.info("react result is {}",welcomeWebClient.getResult());
}
}