Search in sources :

Example 1 with ConnectionObserver

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

the class HttpResourcesTest method before.

@BeforeEach
void before() {
    loopDisposed = new AtomicBoolean();
    poolDisposed = new AtomicBoolean();
    LoopResources loopResources = new LoopResources() {

        @Override
        public EventLoopGroup onServer(boolean useNative) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Mono<Void> disposeLater(Duration quietPeriod, Duration timeout) {
            return Mono.<Void>empty().doOnSuccess(c -> loopDisposed.set(true));
        }

        @Override
        public boolean isDisposed() {
            return loopDisposed.get();
        }
    };
    ConnectionProvider poolResources = new ConnectionProvider() {

        @Override
        public Mono<? extends Connection> acquire(TransportConfig config, ConnectionObserver observer, @Nullable Supplier<? extends SocketAddress> remoteAddress, @Nullable AddressResolverGroup<?> resolverGroup) {
            return Mono.never();
        }

        @Override
        public Mono<Void> disposeLater() {
            return Mono.<Void>empty().doOnSuccess(c -> poolDisposed.set(true));
        }

        @Override
        public boolean isDisposed() {
            return poolDisposed.get();
        }
    };
    testResources = new HttpResources(loopResources, poolResources);
}
Also used : AddressResolverGroup(io.netty.resolver.AddressResolverGroup) Duration(java.time.Duration) ConnectionProvider(reactor.netty.resources.ConnectionProvider) TransportConfig(reactor.netty.transport.TransportConfig) ConnectionObserver(reactor.netty.ConnectionObserver) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LoopResources(reactor.netty.resources.LoopResources) Supplier(java.util.function.Supplier) SocketAddress(java.net.SocketAddress) Nullable(reactor.util.annotation.Nullable) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with ConnectionObserver

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

the class DefaultPooledConnectionProviderTest method testRetryConnect.

@Test
@SuppressWarnings("unchecked")
void testRetryConnect() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(1);
    InetSocketAddress address = AddressUtils.createUnresolved("localhost", 12122);
    AddressResolverGroup<SocketAddress> resolverGroup = Mockito.mock(AddressResolverGroup.class);
    AddressResolver<SocketAddress> resolver = Mockito.mock(AddressResolver.class);
    io.netty.util.concurrent.Future<List<SocketAddress>> resolveFuture = Mockito.mock(io.netty.util.concurrent.Future.class);
    List<SocketAddress> resolveAllResult = Arrays.asList(// connection refused
    new InetSocketAddress(NetUtil.LOCALHOST4, 12122), // connection refused
    new InetSocketAddress(NetUtil.LOCALHOST6, 12122), // connection established
    new InetSocketAddress("example.com", 80));
    Mockito.when(resolverGroup.getResolver(group.next())).thenReturn(resolver);
    Mockito.when(resolver.isSupported(address)).thenReturn(true);
    Mockito.when(resolver.isResolved(address)).thenReturn(false);
    Mockito.when(resolver.resolveAll(address)).thenReturn(resolveFuture);
    Mockito.when(resolveFuture.isDone()).thenReturn(true);
    Mockito.when(resolveFuture.cause()).thenReturn(null);
    Mockito.when(resolveFuture.getNow()).thenReturn(resolveAllResult);
    ConnectionProvider pool = ConnectionProvider.create("testRetryConnect", 1);
    Supplier<? extends SocketAddress> remoteAddress = () -> address;
    ConnectionObserver observer = ConnectionObserver.emptyListener();
    ClientTransportConfigImpl config = new ClientTransportConfigImpl(group, pool, Collections.emptyMap(), remoteAddress, resolverGroup);
    Connection conn = null;
    try {
        conn = pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(5));
        assertThat(((InetSocketAddress) conn.address()).getHostString()).isEqualTo("example.com");
    } finally {
        if (conn != null) {
            conn.disposeNow(Duration.ofSeconds(5));
        }
        pool.disposeLater().block(Duration.ofSeconds(5));
        group.shutdownGracefully().get(5, TimeUnit.SECONDS);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) Connection(reactor.netty.Connection) ConnectionObserver(reactor.netty.ConnectionObserver) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) List(java.util.List) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 3 with ConnectionObserver

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

the class DefaultPooledConnectionProviderTest method fixedPoolTwoAcquire.

@Test
void fixedPoolTwoAcquire() throws Exception {
    final ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
    int echoServerPort = SocketUtils.findAvailableTcpPort();
    TcpClientTests.EchoServer echoServer = new TcpClientTests.EchoServer(echoServerPort);
    EventLoopGroup group = new NioEventLoopGroup(2);
    java.util.concurrent.Future<?> f1 = null;
    java.util.concurrent.Future<?> f2 = null;
    Future<?> sf = null;
    try (AddressResolverGroup<?> resolver = NameResolverProvider.builder().build().newNameResolverGroup(TcpResources.get(), true)) {
        final InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", echoServerPort);
        ConnectionProvider pool = ConnectionProvider.create("fixedPoolTwoAcquire", 2);
        Supplier<? extends SocketAddress> remoteAddress = () -> address;
        ConnectionObserver observer = ConnectionObserver.emptyListener();
        ClientTransportConfigImpl config = new ClientTransportConfigImpl(group, pool, Collections.emptyMap(), remoteAddress, resolver);
        // fail a couple
        StepVerifier.create(pool.acquire(config, observer, remoteAddress, config.resolverInternal())).verifyErrorMatches(msg -> msg.getCause() instanceof ConnectException);
        StepVerifier.create(pool.acquire(config, observer, remoteAddress, config.resolverInternal())).verifyErrorMatches(msg -> msg.getCause() instanceof ConnectException);
        // start the echo server
        f1 = service.submit(echoServer);
        Thread.sleep(100);
        // acquire 2
        final PooledConnection c1 = (PooledConnection) pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(30));
        assertThat(c1).isNotNull();
        final PooledConnection c2 = (PooledConnection) pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(30));
        assertThat(c2).isNotNull();
        // make room for 1 more
        c2.disposeNow();
        final PooledConnection c3 = (PooledConnection) pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(30));
        assertThat(c3).isNotNull();
        // next one will block until a previous one is released
        long start = System.currentTimeMillis();
        sf = service.schedule(() -> c1.onStateChange(c1, ConnectionObserver.State.DISCONNECTING), 500, TimeUnit.MILLISECONDS);
        final PooledConnection c4 = (PooledConnection) pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(30));
        assertThat(c4).isNotNull();
        long end = System.currentTimeMillis();
        assertThat(end - start).as("channel4 acquire blocked until channel1 released").isGreaterThanOrEqualTo(500);
        c3.onStateChange(c3, ConnectionObserver.State.DISCONNECTING);
        c4.onStateChange(c4, ConnectionObserver.State.DISCONNECTING);
        assertThat(c1).isEqualTo(c4);
        assertThat(c1.pool).isEqualTo(c2.pool).isEqualTo(c3.pool).isEqualTo(c4.pool);
        InstrumentedPool<PooledConnection> defaultPool = c1.pool;
        CountDownLatch latch = new CountDownLatch(1);
        f2 = service.submit(() -> {
            while (defaultPool.metrics().acquiredSize() > 0) {
                LockSupport.parkNanos(100);
            }
            latch.countDown();
        });
        assertThat(latch.await(5, TimeUnit.SECONDS)).as("activeConnections fully released").isTrue();
    } finally {
        service.shutdownNow();
        echoServer.close();
        group.shutdownGracefully().get(5, TimeUnit.SECONDS);
        assertThat(f1).isNotNull();
        assertThat(f1.get()).isNull();
        assertThat(f2).isNotNull();
        assertThat(f2.get()).isNull();
        assertThat(sf).isNotNull();
        assertThat(sf.get()).isNull();
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TcpClientTests(reactor.netty.tcp.TcpClientTests) InetSocketAddress(java.net.InetSocketAddress) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectionObserver(reactor.netty.ConnectionObserver) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ConnectException(java.net.ConnectException) Test(org.junit.jupiter.api.Test)

Example 4 with ConnectionObserver

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

the class DefaultPooledConnectionProviderTest method testDisposeInactivePoolsInBackground.

@Test
void testDisposeInactivePoolsInBackground() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(1);
    InetSocketAddress address = AddressUtils.createUnresolved("example.com", 80);
    ConnectionProvider.Builder builder = ConnectionProvider.builder("testDisposeInactivePoolsInBackground").maxConnections(1).disposeInactivePoolsInBackground(Duration.ofMillis(100), Duration.ofSeconds(1));
    VirtualTimeScheduler vts = VirtualTimeScheduler.create();
    DefaultPooledConnectionProvider pool = new DefaultPooledConnectionProvider(builder, SchedulerClock.of(vts));
    Supplier<? extends SocketAddress> remoteAddress = () -> address;
    ConnectionObserver observer = ConnectionObserver.emptyListener();
    ClientTransportConfigImpl config = new ClientTransportConfigImpl(group, pool, Collections.emptyMap(), remoteAddress, DefaultAddressResolverGroup.INSTANCE);
    Connection conn = null;
    try {
        conn = pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(5));
        assertThat(((InetSocketAddress) conn.address()).getHostString()).isEqualTo("example.com");
    } finally {
        if (conn != null) {
            CountDownLatch latch = new CountDownLatch(1);
            conn.channel().close().addListener(f -> latch.countDown());
            assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
        }
        assertThat(pool.channelPools.size()).isEqualTo(1);
        vts.advanceTimeBy(Duration.ofSeconds(5));
        await().atMost(500, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS).untilAsserted(() -> assertThat(pool.channelPools.size()).isEqualTo(0));
        pool.disposeLater().block(Duration.ofSeconds(5));
        group.shutdownGracefully().get(5, TimeUnit.SECONDS);
    }
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) VirtualTimeScheduler(reactor.test.scheduler.VirtualTimeScheduler) InetSocketAddress(java.net.InetSocketAddress) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 5 with ConnectionObserver

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

the class UdpServerBind method bind.

@Override
public Mono<? extends Connection> bind() {
    UdpServerConfig conf = configuration();
    ConnectionObserver observer = config.defaultConnectionObserver().then(config.connectionObserver());
    Mono<? extends Connection> mono = ConnectionProvider.newConnection().acquire(conf, observer, null, null);
    if (conf.doOnBind() != null) {
        mono = mono.doOnSubscribe(s -> conf.doOnBind().accept(conf));
    }
    return mono;
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) ConnectionObserver(reactor.netty.ConnectionObserver) ChannelOption(io.netty.channel.ChannelOption) NetUtil(io.netty.util.NetUtil) Mono(reactor.core.publisher.Mono) Connection(reactor.netty.Connection) ConnectionProvider(reactor.netty.resources.ConnectionProvider) InetSocketAddress(java.net.InetSocketAddress) Collections(java.util.Collections)

Aggregations

ConnectionObserver (reactor.netty.ConnectionObserver)16 Connection (reactor.netty.Connection)9 InetSocketAddress (java.net.InetSocketAddress)7 SocketAddress (java.net.SocketAddress)7 Duration (java.time.Duration)6 Mono (reactor.core.publisher.Mono)5 EventLoopGroup (io.netty.channel.EventLoopGroup)4 AddressResolverGroup (io.netty.resolver.AddressResolverGroup)4 Supplier (java.util.function.Supplier)4 ConnectionProvider (reactor.netty.resources.ConnectionProvider)4 LoopResources (reactor.netty.resources.LoopResources)4 Channel (io.netty.channel.Channel)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 List (java.util.List)3 Objects (java.util.Objects)3 TimeUnit (java.util.concurrent.TimeUnit)3 Test (org.junit.jupiter.api.Test)3 CoreSubscriber (reactor.core.CoreSubscriber)3 PooledConnection (reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection)3 TransportConfig (reactor.netty.transport.TransportConfig)3