Search in sources :

Example 76 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class ServerTransport method bindUntilJavaShutdown.

/**
 * Start the server in a fully blocking fashion, not only waiting for it to initialize
 * but also blocking during the full lifecycle of the server. Since most
 * servers will be long-lived, this is more adapted to running a server out of a main
 * method, only allowing shutdown of the servers through {@code sigkill}.
 * <p>
 * Note: {@link Runtime#addShutdownHook(Thread) JVM shutdown hook} is added by
 * this method in order to properly disconnect the server upon receiving a
 * {@code sigkill} signal.</p>
 *
 * @param timeout a timeout for server shutdown
 * @param onStart an optional callback on server start
 */
public final void bindUntilJavaShutdown(Duration timeout, @Nullable Consumer<DisposableServer> onStart) {
    Objects.requireNonNull(timeout, "timeout");
    DisposableServer facade = Objects.requireNonNull(bindNow(), "facade");
    if (onStart != null) {
        onStart.accept(facade);
    }
    Runtime.getRuntime().addShutdownHook(new Thread(() -> facade.disposeNow(timeout)));
    facade.onDispose().block();
}
Also used : DisposableServer(reactor.netty.DisposableServer)

Example 77 with DisposableServer

use of reactor.netty.DisposableServer in project spring-boot by spring-projects.

the class GracefulShutdown method shutDownGracefully.

void shutDownGracefully(GracefulShutdownCallback callback) {
    DisposableServer server = this.disposableServer.get();
    if (server == null) {
        return;
    }
    logger.info("Commencing graceful shutdown. Waiting for active requests to complete");
    this.shutdownThread = new Thread(() -> doShutdown(callback, server), "netty-shutdown");
    this.shutdownThread.start();
}
Also used : DisposableServer(reactor.netty.DisposableServer)

Example 78 with DisposableServer

use of reactor.netty.DisposableServer in project spring-framework by spring-projects.

the class ReactorHttpServer method startInternal.

@Override
protected void startInternal() {
    DisposableServer server = this.reactorServer.handle(this.reactorHandler).bind().block();
    setPort(((InetSocketAddress) server.address()).getPort());
    this.serverRef.set(server);
}
Also used : DisposableServer(reactor.netty.DisposableServer)

Example 79 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class ITTracingHttpServerDecoratorTest method init.

@Override
protected void init() {
    HttpServerRoutes routes = HttpServerRoutes.newRoutes().options("/", (req, res) -> res.send()).get("/foo", (req, res) -> res.sendString(Mono.just("bar"))).get("/baggage", (req, res) -> res.sendString(Mono.just(req.requestHeaders().getAsString(BAGGAGE_FIELD_KEY)))).get("/exception", (req, res) -> Mono.error(NOT_READY_ISE)).get("/badrequest", (req, res) -> res.status(400).send()).get("/async", (req, res) -> res.sendString(Mono.just("body").publishOn(Schedulers.boundedElastic()))).get("/exceptionAsync", (req, res) -> Mono.error(NOT_READY_ISE).publishOn(Schedulers.boundedElastic()).then()).get("/items/{itemId}", (req, res) -> res.sendString(Mono.justOrEmpty(req.param("itemId")))).get("/async_items/{itemId}", (req, res) -> res.sendString(Mono.justOrEmpty(req.param("itemId")).publishOn(Schedulers.boundedElastic()))).get("/nested/items/{itemId}", (req, res) -> res.sendString(Mono.justOrEmpty(req.param("itemId")))).get("/child", (req, res) -> {
        httpTracing.tracing().tracer().nextSpan().name("child").start().finish();
        return res.send();
    });
    ReactorNettyHttpTracing reactorNettyHttpTracing = ReactorNettyHttpTracing.create(httpTracing, s -> {
        if ("/foo/bark".equals(s)) {
            return "not_found";
        }
        int ind = s.lastIndexOf('/');
        if (s.length() > 1 && ind > -1) {
            return s.substring(0, ind);
        }
        return s;
    });
    group = new DefaultChannelGroup(executor);
    disposableServer = reactorNettyHttpTracing.decorateHttpServer(HttpServer.create().port(0).wiretap(true).forwarded(true).channelGroup(group).handle(routes)).bindNow();
}
Also used : HttpServerRoutes(reactor.netty.http.server.HttpServerRoutes) EventExecutor(io.netty.util.concurrent.EventExecutor) AfterClass(org.junit.AfterClass) ChannelGroup(io.netty.channel.group.ChannelGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) HttpServer(reactor.netty.http.server.HttpServer) Ignore(org.junit.Ignore) After(org.junit.After) Schedulers(reactor.core.scheduler.Schedulers) DisposableServer(reactor.netty.DisposableServer) HttpServerRoutes(reactor.netty.http.server.HttpServerRoutes) SERVER(brave.Span.Kind.SERVER) ITHttpServer(brave.test.http.ITHttpServer) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup)

Example 80 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpServerTests method testNormalConnectionCloseForWebSocketClient.

@Test
void testNormalConnectionCloseForWebSocketClient() throws Exception {
    Flux<String> flux = Flux.range(0, 100).map(n -> String.format("%010d", n));
    AtomicReference<List<String>> receiver = new AtomicReference<>(new ArrayList<>());
    AtomicReference<WebSocketCloseStatus> statusServer = new AtomicReference<>();
    AtomicReference<WebSocketCloseStatus> statusClient = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(3);
    List<String> test = flux.collectList().block();
    assertThat(test).isNotNull();
    disposableServer = createServer().handle((req, resp) -> resp.sendWebsocket((in, out) -> out.sendString(flux).then(out.sendClose(4404, "test")).then(in.receiveCloseStatus().doOnNext(o -> {
        statusServer.set(o);
        latch.countDown();
    }).then()))).bindNow();
    createClient(disposableServer.port()).websocket().uri("/").handle((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusClient.set(o);
            latch.countDown();
        }).subscribe();
        return in.receive().asString().doOnNext(s -> receiver.get().add(s)).doFinally(sig -> latch.countDown()).then(Mono.delay(Duration.ofMillis(500)));
    }).blockLast();
    assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
    assertThat(receiver.get()).containsAll(test);
    assertThat(statusClient.get()).isNotNull().isEqualTo(new WebSocketCloseStatus(4404, "test"));
    assertThat(statusServer.get()).isNotNull().isEqualTo(new WebSocketCloseStatus(4404, "test"));
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Aggregations

DisposableServer (reactor.netty.DisposableServer)137 Mono (reactor.core.publisher.Mono)84 Test (org.junit.jupiter.api.Test)79 Duration (java.time.Duration)71 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)71 AtomicReference (java.util.concurrent.atomic.AtomicReference)68 Flux (reactor.core.publisher.Flux)68 Connection (reactor.netty.Connection)67 TimeUnit (java.util.concurrent.TimeUnit)65 LoopResources (reactor.netty.resources.LoopResources)60 List (java.util.List)58 CountDownLatch (java.util.concurrent.CountDownLatch)57 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)56 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)55 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)54 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)54 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)53 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)53 Assumptions.assumeThat (org.assertj.core.api.Assumptions.assumeThat)53 StepVerifier (reactor.test.StepVerifier)53