Search in sources :

Example 6 with StatefulConnection

use of io.lettuce.core.api.StatefulConnection in project lettuce-core by lettuce-io.

the class ReactiveBackpressurePropagationUnitTests method writeCommandAndCancelInTheMiddle.

@Test
void writeCommandAndCancelInTheMiddle() throws Exception {
    Command<String, String, List<String>> lrange = new Command<>(CommandType.LRANGE, new ValueListOutput<>(StringCodec.UTF8));
    RedisPublisher<String, String, String> publisher = new RedisPublisher<>(lrange, statefulConnection, true, ImmediateEventExecutor.INSTANCE);
    CountDownLatch pressureArrived = new CountDownLatch(1);
    CountDownLatch buildPressure = new CountDownLatch(1);
    CountDownLatch waitForPressureReduced = new CountDownLatch(2);
    Disposable cancellation = Flux.from(publisher).limitRate(2).publishOn(Schedulers.single()).doOnNext(s -> {
        try {
            pressureArrived.countDown();
            buildPressure.await();
        } catch (InterruptedException e) {
        }
        waitForPressureReduced.countDown();
    }).subscribe();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    // produce some back pressure
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.arrayHeader(4)));
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("one")));
    pressureArrived.await();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("two")));
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("three")));
    assertThat(embeddedChannel.config().isAutoRead()).isFalse();
    cancellation.dispose();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    // allow processing
    buildPressure.countDown();
    // emit the last item
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("four")));
    // done
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
}
Also used : Disposable(reactor.core.Disposable) ClientResources(io.lettuce.core.resource.ClientResources) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers(org.mockito.ArgumentMatchers) Disposable(reactor.core.Disposable) StringCodec(io.lettuce.core.codec.StringCodec) CommandType(io.lettuce.core.protocol.CommandType) Mock(org.mockito.Mock) CommandLatencyCollector(io.lettuce.core.metrics.CommandLatencyCollector) StatefulConnection(io.lettuce.core.api.StatefulConnection) Command(io.lettuce.core.protocol.Command) Unpooled(io.netty.buffer.Unpooled) LocalAddress(io.netty.channel.local.LocalAddress) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ImmediateEventExecutor(io.netty.util.concurrent.ImmediateEventExecutor) Assertions(org.assertj.core.api.Assertions) Schedulers(reactor.core.scheduler.Schedulers) Tracing(io.lettuce.core.tracing.Tracing) CommandHandler(io.lettuce.core.protocol.CommandHandler) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Endpoint(io.lettuce.core.protocol.Endpoint) ValueListOutput(io.lettuce.core.output.ValueListOutput) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) List(java.util.List) RedisCommand(io.lettuce.core.protocol.RedisCommand) Command(io.lettuce.core.protocol.Command) RedisCommand(io.lettuce.core.protocol.RedisCommand) List(java.util.List) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 7 with StatefulConnection

use of io.lettuce.core.api.StatefulConnection in project lettuce-core by lettuce-io.

the class ReactiveBackpressurePropagationUnitTests method writeCommand.

@Test
void writeCommand() throws Exception {
    Command<String, String, List<String>> lrange = new Command<>(CommandType.LRANGE, new ValueListOutput<>(StringCodec.UTF8));
    RedisPublisher<String, String, String> publisher = new RedisPublisher<>((Command) lrange, statefulConnection, true, ImmediateEventExecutor.INSTANCE);
    CountDownLatch pressureArrived = new CountDownLatch(1);
    CountDownLatch buildPressure = new CountDownLatch(1);
    CountDownLatch waitForPressureReduced = new CountDownLatch(2);
    CountDownLatch waitForWorkCompleted = new CountDownLatch(4);
    Flux.from(publisher).limitRate(2).publishOn(Schedulers.single()).doOnNext(s -> {
        try {
            pressureArrived.countDown();
            buildPressure.await();
        } catch (InterruptedException e) {
        }
        waitForPressureReduced.countDown();
        waitForWorkCompleted.countDown();
    }).subscribe();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    // produce some back pressure
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.arrayHeader(4)));
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("one")));
    pressureArrived.await();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("two")));
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("three")));
    assertThat(embeddedChannel.config().isAutoRead()).isFalse();
    // allow processing
    buildPressure.countDown();
    // wait until processing caught up
    waitForPressureReduced.await();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
    // emit the last item
    embeddedChannel.writeInbound(Unpooled.wrappedBuffer(RESP.bulkString("four")));
    // done
    waitForWorkCompleted.await();
    assertThat(embeddedChannel.config().isAutoRead()).isTrue();
}
Also used : ClientResources(io.lettuce.core.resource.ClientResources) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers(org.mockito.ArgumentMatchers) Disposable(reactor.core.Disposable) StringCodec(io.lettuce.core.codec.StringCodec) CommandType(io.lettuce.core.protocol.CommandType) Mock(org.mockito.Mock) CommandLatencyCollector(io.lettuce.core.metrics.CommandLatencyCollector) StatefulConnection(io.lettuce.core.api.StatefulConnection) Command(io.lettuce.core.protocol.Command) Unpooled(io.netty.buffer.Unpooled) LocalAddress(io.netty.channel.local.LocalAddress) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ImmediateEventExecutor(io.netty.util.concurrent.ImmediateEventExecutor) Assertions(org.assertj.core.api.Assertions) Schedulers(reactor.core.scheduler.Schedulers) Tracing(io.lettuce.core.tracing.Tracing) CommandHandler(io.lettuce.core.protocol.CommandHandler) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Endpoint(io.lettuce.core.protocol.Endpoint) ValueListOutput(io.lettuce.core.output.ValueListOutput) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) List(java.util.List) RedisCommand(io.lettuce.core.protocol.RedisCommand) Command(io.lettuce.core.protocol.Command) RedisCommand(io.lettuce.core.protocol.RedisCommand) List(java.util.List) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 8 with StatefulConnection

use of io.lettuce.core.api.StatefulConnection in project lettuce-core by lettuce-io.

the class ConnectionDecoratingInvocationHandler method handleInvocation.

@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
    Method targetMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes());
    Method proxyMethod = proxy.getClass().getMethod(method.getName(), method.getParameterTypes());
    Object result = targetMethod.invoke(target, args);
    if (result instanceof StatefulConnection) {
        Class[] interfaces;
        if (result instanceof StatefulRedisClusterConnection && proxyMethod.getReturnType().isAssignableFrom(StatefulRedisClusterConnection.class)) {
            interfaces = new Class[] { StatefulConnection.class, StatefulRedisClusterConnection.class };
        } else if (result instanceof StatefulRedisSentinelConnection && proxyMethod.getReturnType().isAssignableFrom(StatefulRedisSentinelConnection.class)) {
            interfaces = new Class[] { StatefulConnection.class, StatefulRedisSentinelConnection.class };
        } else {
            interfaces = new Class[] { StatefulConnection.class, StatefulRedisConnection.class };
        }
        return Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new ConnectionDecoratingInvocationHandler(result));
    }
    return result;
}
Also used : StatefulRedisClusterConnection(io.lettuce.core.cluster.api.StatefulRedisClusterConnection) StatefulConnection(io.lettuce.core.api.StatefulConnection) StatefulRedisSentinelConnection(io.lettuce.core.sentinel.api.StatefulRedisSentinelConnection) Method(java.lang.reflect.Method) StatefulRedisConnection(io.lettuce.core.api.StatefulRedisConnection)

Example 9 with StatefulConnection

use of io.lettuce.core.api.StatefulConnection in project lettuce-core by lettuce-io.

the class LettuceExtension method afterAll.

@Override
public void afterAll(ExtensionContext context) {
    ExtensionContext.Store store = getStore(context);
    CLOSE_AFTER_EACH.forEach(it -> {
        StatefulConnection connection = store.get(it, StatefulConnection.class);
        if (connection != null) {
            connection.close();
            store.remove(StatefulRedisConnection.class);
        }
    });
}
Also used : StatefulConnection(io.lettuce.core.api.StatefulConnection)

Example 10 with StatefulConnection

use of io.lettuce.core.api.StatefulConnection in project lcache by long172066912.

the class TestRedisCache2 method testPubSub.

@Test
public void testPubSub() {
    for (int p = 0; p < 10; p++) {
        int finalP = p;
        new Thread(() -> {
            BaseCacheExecutor baseCacheExecutor = null;
            if (finalP % 2 == 0) {
                baseCacheExecutor = CacheClientFactory.getCacheExecutor(CacheConfigModel.newCache("test"), new LettuceConnectSourceConfig());
            } else {
                baseCacheExecutor = CacheClientFactory.getCacheExecutor(CacheConfigModel.newCache("friend"));
            }
            int i = 0;
            while (true) {
                i++;
                System.out.println("Lettuce发布消息:" + i);
                try {
                    baseCacheExecutor.publish("test", "test" + i);
                    Thread.sleep(1000L);
                } catch (Exception e) {
                    e.printStackTrace();
                    StatefulConnection connectResource = (StatefulConnection) baseCacheExecutor.getConnectResource();
                    if (!connectResource.isOpen()) {
                        System.out.println("关闭连接" + connectResource);
                        baseCacheExecutor.close();
                    }
                    baseCacheExecutor.returnConnectResource();
                }
            }
        }).start();
    }
    new Thread(() -> {
        BaseCacheExecutor baseCacheExecutor = null;
        baseCacheExecutor = CacheClientFactory.getCacheExecutor(CacheConfigModel.newCache("test"), new LettuceConnectSourceConfig());
        baseCacheExecutor.subscribe((message) -> {
            System.out.println("Lettuce Local订阅消息:" + message);
        }, "test");
    }).start();
    new Thread(() -> {
        BaseCacheExecutor baseCacheExecutor = null;
        baseCacheExecutor = CacheClientFactory.getCacheExecutor(CacheConfigModel.newCache("friend"));
        baseCacheExecutor.subscribe((message) -> {
            System.out.println("Lettuce Dev订阅消息:" + message);
        }, "test");
    }).start();
    while (true) {
    }
}
Also used : RScoredSortedSet(org.redisson.api.RScoredSortedSet) PipelineZremRangeByScore(com.lcache.extend.handle.pipeline.PipelineZremRangeByScore) Arrays(java.util.Arrays) PipelineGet(com.lcache.extend.handle.pipeline.PipelineGet) StringCodec(org.redisson.client.codec.StringCodec) LettuceConnectSourceConfig(com.lcache.extend.handle.redis.lettuce.config.LettuceConnectSourceConfig) CompletableFuture(java.util.concurrent.CompletableFuture) JedisConnectSourceConfig(com.lcache.extend.handle.redis.jedis.config.JedisConnectSourceConfig) StatefulConnection(io.lettuce.core.api.StatefulConnection) ArrayList(java.util.ArrayList) RLock(org.redisson.api.RLock) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) RedissonClient(org.redisson.api.RedissonClient) CacheClientFactory(com.lcache.client.CacheClientFactory) CacheConfigModel(com.lcache.core.model.CacheConfigModel) LcacheCaffeineLocalCache(com.lcache.core.cache.localcache.LcacheCaffeineLocalCache) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test) Collectors(java.util.stream.Collectors) PipelineCmd(com.lcache.extend.handle.pipeline.PipelineCmd) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) JSON(com.alibaba.fastjson.JSON) BaseCacheExecutor(com.lcache.core.BaseCacheExecutor) Assert.assertEquals(org.junit.Assert.assertEquals) BaseCacheExecutor(com.lcache.core.BaseCacheExecutor) StatefulConnection(io.lettuce.core.api.StatefulConnection) LettuceConnectSourceConfig(com.lcache.extend.handle.redis.lettuce.config.LettuceConnectSourceConfig) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

StatefulConnection (io.lettuce.core.api.StatefulConnection)12 List (java.util.List)3 Test (org.junit.jupiter.api.Test)3 CacheConfigModel (com.lcache.core.model.CacheConfigModel)2 StringCodec (io.lettuce.core.codec.StringCodec)2 CommandLatencyCollector (io.lettuce.core.metrics.CommandLatencyCollector)2 ValueListOutput (io.lettuce.core.output.ValueListOutput)2 Command (io.lettuce.core.protocol.Command)2 CommandHandler (io.lettuce.core.protocol.CommandHandler)2 CommandType (io.lettuce.core.protocol.CommandType)2 Endpoint (io.lettuce.core.protocol.Endpoint)2 RedisCommand (io.lettuce.core.protocol.RedisCommand)2 ClientResources (io.lettuce.core.resource.ClientResources)2 Tracing (io.lettuce.core.tracing.Tracing)2 Unpooled (io.netty.buffer.Unpooled)2 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)2 LocalAddress (io.netty.channel.local.LocalAddress)2 ImmediateEventExecutor (io.netty.util.concurrent.ImmediateEventExecutor)2 ArrayList (java.util.ArrayList)2 CountDownLatch (java.util.concurrent.CountDownLatch)2