在我的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/
答案 0 :(得分:2)
您无需在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();