在我的 Java 应用程序中,我使用 Spring Webflux 作为依赖项,例如:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
</dependencies>
使用 2.0.6.RELEASE 版本,我可以使用以下代码启动 Netty 服务器:
public static void main(String[] args) {
RouterFunction<?> route;
route = route(GET("/hello"),
request -> {
Mono<String> hi = Mono.just("hi");
return ServerResponse.ok().contentType(TEXT_PLAIN).body(hi, String.class);
});
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter =
new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create("localhost", 8080);
server.startAndAwait(adapter);
}
但在 2.1.0 中它无法编译。我也尝试过类似的方法,但仍然无法使其工作。
HttpServer
.create()
.host("localhost")
.port(8080)
.handle(adapter)
.bind()
.block();
如何启动Netty服务器?
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-httphandler https://projectreactor.io/docs/netty/release/api/
最佳答案
您不需要在 Spring Boot 应用程序中手动启动服务器,只需将 RouterFunction
声明为 @Bean
即可,如下所示:
@Bean
public RouterFunction<ServerResponse> hello() {
return route(GET("/hello"),
request -> {
Mono<String> hi = Mono.just("hi");
return ServerResponse.ok().contentType(TEXT_PLAIN).body(hi, String.class);
});
}
Spring Boot 使您免受支持服务器中底层 API 更改的影响。
这里的 main 方法看起来不像典型的 Spring Boot main 方法,所以我认为您实际上并没有在这里使用 Spring Boot。无论如何,这里有一个代码片段可以解决您的问题;从 Reactor Netty 0.8 开始,bind() 部分与实际等待部分分开:
RouterFunction<?> route = RouterFunctions.route(RequestPredicates.GET("/hello"),
request -> {
Mono<String> hi = Mono.just("hi");
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(hi, String.class);
});
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter =
new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create().host("localhost").port(8080);
DisposableServer disposableServer = server.handle(adapter).bind().block();
disposableServer.onDispose().block();
关于java - 无法在 Spring Webflux 2.1.0.RELEASE 中启动 Netty 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426206/