Search in sources :

Example 11 with RedisConnection

use of org.redisson.client.RedisConnection in project redisson by redisson.

the class ClusterConnectionManager method addMasterEntry.

private RFuture<Collection<RFuture<Void>>> addMasterEntry(final ClusterPartition partition, final ClusterServersConfig cfg) {
    if (partition.isMasterFail()) {
        RedisException e = new RedisException("Failed to add master: " + partition.getMasterAddress() + " for slot ranges: " + partition.getSlotRanges() + ". Reason - server has FAIL flag");
        if (partition.getSlotRanges().isEmpty()) {
            e = new RedisException("Failed to add master: " + partition.getMasterAddress() + ". Reason - server has FAIL flag");
        }
        return newFailedFuture(e);
    }
    final RPromise<Collection<RFuture<Void>>> result = newPromise();
    RFuture<RedisConnection> connectionFuture = connect(cfg, partition.getMasterAddress());
    connectionFuture.addListener(new FutureListener<RedisConnection>() {

        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                log.error("Can't connect to master: {} with slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
                result.tryFailure(future.cause());
                return;
            }
            final RedisConnection connection = future.getNow();
            RFuture<Map<String, String>> clusterFuture = connection.async(RedisCommands.CLUSTER_INFO);
            clusterFuture.addListener(new FutureListener<Map<String, String>>() {

                @Override
                public void operationComplete(Future<Map<String, String>> future) throws Exception {
                    if (!future.isSuccess()) {
                        log.error("Can't execute CLUSTER_INFO for " + connection.getRedisClient().getAddr(), future.cause());
                        result.tryFailure(future.cause());
                        return;
                    }
                    Map<String, String> params = future.getNow();
                    if ("fail".equals(params.get("cluster_state"))) {
                        RedisException e = new RedisException("Failed to add master: " + partition.getMasterAddress() + " for slot ranges: " + partition.getSlotRanges() + ". Reason - cluster_state:fail");
                        log.error("cluster_state:fail for " + connection.getRedisClient().getAddr());
                        result.tryFailure(e);
                        return;
                    }
                    MasterSlaveServersConfig config = create(cfg);
                    config.setMasterAddress(partition.getMasterAddress());
                    final MasterSlaveEntry e;
                    List<RFuture<Void>> futures = new ArrayList<RFuture<Void>>();
                    if (config.getReadMode() == ReadMode.MASTER) {
                        e = new SingleEntry(partition.getSlotRanges(), ClusterConnectionManager.this, config);
                    } else {
                        config.setSlaveAddresses(partition.getSlaveAddresses());
                        e = new MasterSlaveEntry(partition.getSlotRanges(), ClusterConnectionManager.this, config);
                        List<RFuture<Void>> fs = e.initSlaveBalancer(partition.getFailedSlaveAddresses());
                        futures.addAll(fs);
                        if (!partition.getSlaveAddresses().isEmpty()) {
                            log.info("slaves: {} added for slot ranges: {}", partition.getSlaveAddresses(), partition.getSlotRanges());
                            if (!partition.getFailedSlaveAddresses().isEmpty()) {
                                log.warn("slaves: {} is down for slot ranges: {}", partition.getFailedSlaveAddresses(), partition.getSlotRanges());
                            }
                        }
                    }
                    RFuture<Void> f = e.setupMasterEntry(config.getMasterAddress().getHost(), config.getMasterAddress().getPort());
                    final RPromise<Void> initFuture = newPromise();
                    futures.add(initFuture);
                    f.addListener(new FutureListener<Void>() {

                        @Override
                        public void operationComplete(Future<Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                log.error("Can't add master: {} for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
                                initFuture.tryFailure(future.cause());
                                return;
                            }
                            for (Integer slot : partition.getSlots()) {
                                addEntry(slot, e);
                                lastPartitions.put(slot, partition);
                            }
                            log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(), partition.getSlotRanges());
                            if (!initFuture.trySuccess(null)) {
                                throw new IllegalStateException();
                            }
                        }
                    });
                    if (!result.trySuccess(futures)) {
                        throw new IllegalStateException();
                    }
                }
            });
        }
    });
    return result;
}
Also used : ArrayList(java.util.ArrayList) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) RedisException(org.redisson.client.RedisException) FutureListener(io.netty.util.concurrent.FutureListener) SingleEntry(org.redisson.connection.SingleEntry) MasterSlaveServersConfig(org.redisson.config.MasterSlaveServersConfig) RFuture(org.redisson.api.RFuture) RedisException(org.redisson.client.RedisException) RedisConnectionException(org.redisson.client.RedisConnectionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Collection(java.util.Collection) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisConnection(org.redisson.client.RedisConnection)

Example 12 with RedisConnection

use of org.redisson.client.RedisConnection in project redisson by redisson.

the class SpringNamespaceTest method testAutowireRedis.

@Test
public void testAutowireRedis() {
    AutowireRedis bean = context.getAutowireCapableBeanFactory().getBean(AutowireRedis.class);
    RedisConnection connection = bean.getRedisClient().connect();
    assertTrue(connection.isActive());
    connection.closeAsync().awaitUninterruptibly();
}
Also used : RedisConnection(org.redisson.client.RedisConnection) BaseTest(org.redisson.BaseTest) Test(org.junit.Test)

Example 13 with RedisConnection

use of org.redisson.client.RedisConnection in project redisson by redisson.

the class RedisClientTest method testConnectAsync.

@Test
public void testConnectAsync() throws InterruptedException {
    RedisClient c = new RedisClient(RedisRunner.getDefaultRedisServerBindAddressAndPort());
    RFuture<RedisConnection> f = c.connectAsync();
    final CountDownLatch l = new CountDownLatch(1);
    f.addListener((FutureListener<RedisConnection>) future -> {
        RedisConnection conn = future.get();
        assertThat(conn.sync(RedisCommands.PING)).isEqualTo("PONG");
        l.countDown();
    });
    assertThat(l.await(10, TimeUnit.SECONDS)).isTrue();
}
Also used : RedisClient(org.redisson.client.RedisClient) PubSubType(org.redisson.client.protocol.pubsub.PubSubType) RPromise(org.redisson.misc.RPromise) Arrays(java.util.Arrays) RedisConnection(org.redisson.client.RedisConnection) BeforeClass(org.junit.BeforeClass) StringCodec(org.redisson.client.codec.StringCodec) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RedisClient(org.redisson.client.RedisClient) ArrayList(java.util.ArrayList) RFuture(org.redisson.api.RFuture) RedisPubSubListener(org.redisson.client.RedisPubSubListener) Map(java.util.Map) After(org.junit.After) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) RedisPubSubConnection(org.redisson.client.RedisPubSubConnection) AfterClass(org.junit.AfterClass) LongCodec(org.redisson.client.codec.LongCodec) FutureListener(io.netty.util.concurrent.FutureListener) RedissonPromise(org.redisson.misc.RedissonPromise) IOException(java.io.IOException) Test(org.junit.Test) CommandData(org.redisson.client.protocol.CommandData) Executors(java.util.concurrent.Executors) RedisCommands(org.redisson.client.protocol.RedisCommands) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CommandsData(org.redisson.client.protocol.CommandsData) CountDownLatch(java.util.concurrent.CountDownLatch) RedisConnection(org.redisson.client.RedisConnection) Test(org.junit.Test)

Example 14 with RedisConnection

use of org.redisson.client.RedisConnection in project redisson by redisson.

the class RedisNodes method pingAll.

@Override
public boolean pingAll() {
    List<RedisClientEntry> clients = new ArrayList<RedisClientEntry>(connectionManager.getClients());
    final Map<RedisConnection, RFuture<String>> result = new ConcurrentHashMap<RedisConnection, RFuture<String>>(clients.size());
    final CountDownLatch latch = new CountDownLatch(clients.size());
    for (RedisClientEntry entry : clients) {
        RFuture<RedisConnection> f = entry.getClient().connectAsync();
        f.addListener(new FutureListener<RedisConnection>() {

            @Override
            public void operationComplete(Future<RedisConnection> future) throws Exception {
                if (future.isSuccess()) {
                    final RedisConnection c = future.getNow();
                    RPromise<RedisConnection> connectionFuture = connectionManager.newPromise();
                    connectionManager.getConnectListener().onConnect(connectionFuture, c, null, connectionManager.getConfig());
                    connectionFuture.addListener(new FutureListener<RedisConnection>() {

                        @Override
                        public void operationComplete(Future<RedisConnection> future) throws Exception {
                            RFuture<String> r = c.async(connectionManager.getConfig().getPingTimeout(), RedisCommands.PING);
                            result.put(c, r);
                            latch.countDown();
                        }
                    });
                } else {
                    latch.countDown();
                }
            }
        });
    }
    long time = System.currentTimeMillis();
    try {
        latch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    if (System.currentTimeMillis() - time >= connectionManager.getConfig().getConnectTimeout()) {
        for (Entry<RedisConnection, RFuture<String>> entry : result.entrySet()) {
            entry.getKey().closeAsync();
        }
        return false;
    }
    time = System.currentTimeMillis();
    boolean res = true;
    for (Entry<RedisConnection, RFuture<String>> entry : result.entrySet()) {
        RFuture<String> f = entry.getValue();
        f.awaitUninterruptibly();
        if (!"PONG".equals(f.getNow())) {
            res = false;
        }
        entry.getKey().closeAsync();
    }
    // true and no futures missed during client connection
    return res && result.size() == clients.size();
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) RPromise(org.redisson.misc.RPromise) ArrayList(java.util.ArrayList) RFuture(org.redisson.api.RFuture) CountDownLatch(java.util.concurrent.CountDownLatch) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisClientEntry(org.redisson.connection.RedisClientEntry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) RedisConnection(org.redisson.client.RedisConnection)

Example 15 with RedisConnection

use of org.redisson.client.RedisConnection in project redisson by redisson.

the class RedissonNode method retrieveAdresses.

private void retrieveAdresses() {
    ConnectionManager connectionManager = ((Redisson) redisson).getConnectionManager();
    for (MasterSlaveEntry entry : connectionManager.getEntrySet()) {
        RFuture<RedisConnection> readFuture = entry.connectionReadOp(null);
        if (readFuture.awaitUninterruptibly((long) connectionManager.getConfig().getConnectTimeout()) && readFuture.isSuccess()) {
            RedisConnection connection = readFuture.getNow();
            entry.releaseRead(connection);
            remoteAddress = (InetSocketAddress) connection.getChannel().remoteAddress();
            localAddress = (InetSocketAddress) connection.getChannel().localAddress();
            return;
        }
        RFuture<RedisConnection> writeFuture = entry.connectionWriteOp(null);
        if (writeFuture.awaitUninterruptibly((long) connectionManager.getConfig().getConnectTimeout()) && writeFuture.isSuccess()) {
            RedisConnection connection = writeFuture.getNow();
            entry.releaseWrite(connection);
            remoteAddress = (InetSocketAddress) connection.getChannel().remoteAddress();
            localAddress = (InetSocketAddress) connection.getChannel().localAddress();
            return;
        }
    }
}
Also used : ConnectionManager(org.redisson.connection.ConnectionManager) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) RedisConnection(org.redisson.client.RedisConnection)

Aggregations

RedisConnection (org.redisson.client.RedisConnection)23 FutureListener (io.netty.util.concurrent.FutureListener)7 ArrayList (java.util.ArrayList)7 RFuture (org.redisson.api.RFuture)7 RedisClient (org.redisson.client.RedisClient)7 RedisException (org.redisson.client.RedisException)7 Future (io.netty.util.concurrent.Future)6 Test (org.junit.Test)6 RedisConnectionException (org.redisson.client.RedisConnectionException)6 RPromise (org.redisson.misc.RPromise)5 ChannelFuture (io.netty.channel.ChannelFuture)4 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)4 CommandData (org.redisson.client.protocol.CommandData)4 CommandsData (org.redisson.client.protocol.CommandsData)4 RedissonPromise (org.redisson.misc.RedissonPromise)4 ChannelFutureListener (io.netty.channel.ChannelFutureListener)3 Timeout (io.netty.util.Timeout)3 TimerTask (io.netty.util.TimerTask)3 RedisAskException (org.redisson.client.RedisAskException)3 RedisLoadingException (org.redisson.client.RedisLoadingException)3