Search in sources :

Example 1 with StatefulRedisPubSubConnection

use of io.lettuce.core.pubsub.StatefulRedisPubSubConnection in project lettuce-core by lettuce-io.

the class SentinelTopologyRefreshUnitTests method bindWithSentinelRecovery.

@Test
void bindWithSentinelRecovery() {
    StatefulRedisPubSubConnection<String, String> connection2 = mock(StatefulRedisPubSubConnection.class);
    RedisPubSubAsyncCommands<String, String> async2 = mock(RedisPubSubAsyncCommands.class);
    when(connection2.async()).thenReturn(async2);
    AsyncCommand<String, String, Void> command = new AsyncCommand<>(new Command<>(CommandType.PSUBSCRIBE, null));
    command.complete();
    when(async2.psubscribe(anyString())).thenReturn(command);
    sut = new SentinelTopologyRefresh(redisClient, "mymaster", Arrays.asList(host1, host2));
    when(redisClient.connectPubSubAsync(any(StringCodec.class), eq(host2))).thenReturn(ConnectionFuture.from(null, Futures.failed(new RedisConnectionException("err")))).thenReturn(ConnectionFuture.completed(null, connection2));
    sut.bind(refreshRunnable);
    verify(redisClient).connectPubSubAsync(any(), eq(host1));
    verify(redisClient).connectPubSubAsync(any(), eq(host2));
    Map<RedisURI, StatefulRedisPubSubConnection<String, String>> connections = (Map) ReflectionTestUtils.getField(sut, "pubSubConnections");
    PubSubMessageHandler adapter = getMessageHandler();
    adapter.handle("*", "+sentinel", "sentinel c14cc895bb0479c91312cee0e0440b7d99ad367b 127.0.0.1 26380 @ mymaster 127.0.0.1 6483");
    verify(eventExecutors, times(1)).schedule(captor.capture(), anyLong(), any());
    captor.getValue().run();
    verify(redisClient, times(2)).connectPubSubAsync(any(), eq(host2));
    assertThat(connections).containsKey(host1).containsKey(host2).hasSize(2);
    verify(refreshRunnable, never()).run();
}
Also used : RedisURI(io.lettuce.core.RedisURI) AsyncCommand(io.lettuce.core.protocol.AsyncCommand) PubSubMessageHandler(io.lettuce.core.masterreplica.SentinelTopologyRefresh.PubSubMessageHandler) Mockito.anyString(org.mockito.Mockito.anyString) RedisConnectionException(io.lettuce.core.RedisConnectionException) Map(java.util.Map) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection) Test(org.junit.jupiter.api.Test)

Example 2 with StatefulRedisPubSubConnection

use of io.lettuce.core.pubsub.StatefulRedisPubSubConnection in project lettuce-core by lettuce-io.

the class RedisClient method connectPubSubAsync.

private <K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubAsync(RedisCodec<K, V> codec, RedisURI redisURI, Duration timeout) {
    assertNotNull(codec);
    checkValidRedisURI(redisURI);
    PubSubEndpoint<K, V> endpoint = new PubSubEndpoint<>(getOptions(), getResources());
    RedisChannelWriter writer = endpoint;
    if (CommandExpiryWriter.isSupported(getOptions())) {
        writer = new CommandExpiryWriter(writer, getOptions(), getResources());
    }
    if (CommandListenerWriter.isSupported(getCommandListeners())) {
        writer = new CommandListenerWriter(writer, getCommandListeners());
    }
    StatefulRedisPubSubConnectionImpl<K, V> connection = newStatefulRedisPubSubConnection(endpoint, writer, codec, timeout);
    ConnectionFuture<StatefulRedisPubSubConnection<K, V>> future = connectStatefulAsync(connection, endpoint, redisURI, () -> new PubSubCommandHandler<>(getOptions(), getResources(), codec, endpoint));
    return future.whenComplete((conn, throwable) -> {
        if (throwable != null) {
            conn.close();
        }
    });
}
Also used : CommandExpiryWriter(io.lettuce.core.protocol.CommandExpiryWriter) PubSubEndpoint(io.lettuce.core.pubsub.PubSubEndpoint) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection)

Example 3 with StatefulRedisPubSubConnection

use of io.lettuce.core.pubsub.StatefulRedisPubSubConnection in project lettuce-core by lettuce-io.

the class RedisClusterClient method connectPubSubToNodeAsync.

/**
 * Create a pub/sub connection to a redis socket address.
 *
 * @param codec Use this codec to encode/decode keys and values, must not be {@code null}
 * @param nodeId the nodeId
 * @param socketAddressSupplier supplier for the socket address
 * @param <K> Key type
 * @param <V> Value type
 * @return A new connection
 */
<K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubToNodeAsync(RedisCodec<K, V> codec, String nodeId, Mono<SocketAddress> socketAddressSupplier) {
    assertNotNull(codec);
    assertNotEmpty(initialUris);
    LettuceAssert.notNull(socketAddressSupplier, "SocketAddressSupplier must not be null");
    logger.debug("connectPubSubToNode(" + nodeId + ")");
    PubSubEndpoint<K, V> endpoint = new PubSubEndpoint<>(getClusterClientOptions(), getResources());
    RedisChannelWriter writer = endpoint;
    if (CommandExpiryWriter.isSupported(getClusterClientOptions())) {
        writer = new CommandExpiryWriter(writer, getClusterClientOptions(), getResources());
    }
    if (CommandListenerWriter.isSupported(getCommandListeners())) {
        writer = new CommandListenerWriter(writer, getCommandListeners());
    }
    StatefulRedisPubSubConnectionImpl<K, V> connection = new StatefulRedisPubSubConnectionImpl<>(endpoint, writer, codec, getFirstUri().getTimeout());
    ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectionFuture = connectStatefulAsync(connection, endpoint, getFirstUri(), socketAddressSupplier, () -> new PubSubCommandHandler<>(getClusterClientOptions(), getResources(), codec, endpoint));
    return connectionFuture.whenComplete((conn, throwable) -> {
        if (throwable != null) {
            connection.closeAsync();
        }
    });
}
Also used : CommandExpiryWriter(io.lettuce.core.protocol.CommandExpiryWriter) PubSubEndpoint(io.lettuce.core.pubsub.PubSubEndpoint) StatefulRedisPubSubConnectionImpl(io.lettuce.core.pubsub.StatefulRedisPubSubConnectionImpl) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection)

Example 4 with StatefulRedisPubSubConnection

use of io.lettuce.core.pubsub.StatefulRedisPubSubConnection in project lcache by long172066912.

the class LettuceConnectionFactory method getLettucePubSubConnection.

/**
 * 获取Simple方式发布订阅连接
 *
 * @param redisSourceConfig
 * @return
 */
public StatefulRedisPubSubConnection<String, String> getLettucePubSubConnection(LettuceConnectSourceConfig redisSourceConfig) {
    // 设置线程
    DefaultClientResources res = this.getDefaultClientResources(redisSourceConfig.getHost(), redisSourceConfig.getPort(), redisSourceConfig.getCommonCacheConfig().getIoThreadPoolSize(), redisSourceConfig.getCommonCacheConfig().getComputationThreadPoolSize());
    RedisClient client = RedisClient.create(res, this.getRedisUri(redisSourceConfig.getHost(), redisSourceConfig.getPort(), redisSourceConfig.getPwd(), redisSourceConfig.getDatabase(), redisSourceConfig.getTimeout()));
    client.setOptions(CacheConfigBuildUtils.getClientOptions(redisSourceConfig));
    client.setDefaultTimeout(Duration.ofMillis(redisSourceConfig.getSoTimeout()));
    return (StatefulRedisPubSubConnection<String, String>) this.execute(() -> {
        return client.connectPubSub();
    });
}
Also used : RedisClient(io.lettuce.core.RedisClient) DefaultClientResources(io.lettuce.core.resource.DefaultClientResources) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection)

Example 5 with StatefulRedisPubSubConnection

use of io.lettuce.core.pubsub.StatefulRedisPubSubConnection in project sandbox by backpaper0.

the class DelExpiredEventDemo method main.

public static void main(String[] args) throws Exception {
    RedisClient redisClient = RedisClient.create("redis://localhost:6379");
    CountDownLatch ready = new CountDownLatch(1);
    CountDownLatch shutdown = new CountDownLatch(1);
    new Thread(() -> {
        CountDownLatch latch = new CountDownLatch(3);
        try (StatefulRedisPubSubConnection<String, String> con = redisClient.connectPubSub()) {
            con.addListener(new RedisPubSubAdapter<>() {

                @Override
                public void message(String pattern, String channel, String message) {
                    System.out.printf("pattern=%s, channel=%s, message=%s%n", pattern, channel, message);
                    latch.countDown();
                }
            });
            RedisPubSubCommands<String, String> commands = con.sync();
            commands.psubscribe("__keyevent@*__:del", "__keyevent@*__:expired");
            ready.countDown();
            try {
                latch.await(1, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            shutdown.countDown();
        }
    }).start();
    ready.await(1, TimeUnit.MINUTES);
    try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
        RedisCommands<String, String> commands = connection.sync();
        commands.set("foo", "Hello, world!");
        commands.del("foo");
        commands.setex("bar", 1, "Hello, world!");
        commands.set("baz", "Hello, world!");
        commands.expire("baz", 2);
    }
    shutdown.await(1, TimeUnit.MINUTES);
}
Also used : RedisClient(io.lettuce.core.RedisClient) RedisPubSubAdapter(io.lettuce.core.pubsub.RedisPubSubAdapter) RedisPubSubCommands(io.lettuce.core.pubsub.api.sync.RedisPubSubCommands) CountDownLatch(java.util.concurrent.CountDownLatch) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection)

Aggregations

StatefulRedisPubSubConnection (io.lettuce.core.pubsub.StatefulRedisPubSubConnection)8 RedisURI (io.lettuce.core.RedisURI)4 RedisClient (io.lettuce.core.RedisClient)3 Map (java.util.Map)3 ConnectionFuture (io.lettuce.core.ConnectionFuture)2 RedisConnectionException (io.lettuce.core.RedisConnectionException)2 StringCodec (io.lettuce.core.codec.StringCodec)2 CommandExpiryWriter (io.lettuce.core.protocol.CommandExpiryWriter)2 PubSubEndpoint (io.lettuce.core.pubsub.PubSubEndpoint)2 RedisPubSubAdapter (io.lettuce.core.pubsub.RedisPubSubAdapter)2 ArrayList (java.util.ArrayList)2 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2 Test (org.junit.jupiter.api.Test)2 AsyncCloseable (io.lettuce.core.api.AsyncCloseable)1 EventRecorder (io.lettuce.core.event.jfr.EventRecorder)1 Futures (io.lettuce.core.internal.Futures)1 LettuceLists (io.lettuce.core.internal.LettuceLists)1 PubSubMessageHandler (io.lettuce.core.masterreplica.SentinelTopologyRefresh.PubSubMessageHandler)1 AsyncCommand (io.lettuce.core.protocol.AsyncCommand)1 StatefulRedisPubSubConnectionImpl (io.lettuce.core.pubsub.StatefulRedisPubSubConnectionImpl)1