Search in sources :

Example 1 with RedisClientConfig

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

the class BaseConnectionHandler method channelActive.

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    List<RFuture<Object>> futures = new ArrayList<RFuture<Object>>();
    RedisClientConfig config = redisClient.getConfig();
    if (config.getPassword() != null) {
        RFuture<Object> future;
        if (config.getUsername() != null) {
            future = connection.async(RedisCommands.AUTH, config.getUsername(), config.getPassword());
        } else {
            future = connection.async(RedisCommands.AUTH, config.getPassword());
        }
        futures.add(future);
    }
    if (config.getDatabase() != 0) {
        RFuture<Object> future = connection.async(RedisCommands.SELECT, config.getDatabase());
        futures.add(future);
    }
    if (config.getClientName() != null) {
        RFuture<Object> future = connection.async(RedisCommands.CLIENT_SETNAME, config.getClientName());
        futures.add(future);
    }
    if (config.isReadOnly()) {
        RFuture<Object> future = connection.async(RedisCommands.READONLY);
        futures.add(future);
    }
    if (config.getPingConnectionInterval() > 0) {
        RFuture<Object> future = connection.async(RedisCommands.PING);
        futures.add(future);
    }
    if (futures.isEmpty()) {
        ctx.fireChannelActive();
        connectionPromise.complete(connection);
        return;
    }
    final AtomicBoolean retry = new AtomicBoolean();
    final AtomicInteger commandsCounter = new AtomicInteger(futures.size());
    for (RFuture<Object> future : futures) {
        future.whenComplete((res, e) -> {
            if (e != null) {
                if (e instanceof RedisLoadingException) {
                    if (retry.compareAndSet(false, true)) {
                        ctx.executor().schedule(() -> {
                            channelActive(ctx);
                        }, 1, TimeUnit.SECONDS);
                    }
                    return;
                }
                connection.closeAsync();
                connectionPromise.completeExceptionally(e);
                return;
            }
            if (commandsCounter.decrementAndGet() == 0) {
                ctx.fireChannelActive();
                connectionPromise.complete(connection);
            }
        });
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) RedisClientConfig(org.redisson.client.RedisClientConfig) RFuture(org.redisson.api.RFuture) RedisLoadingException(org.redisson.client.RedisLoadingException)

Example 2 with RedisClientConfig

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

the class RedissonLocalCachedMapTest method testNameMapper.

@Test
public void testNameMapper() throws InterruptedException {
    Config config = new Config();
    config.useSingleServer().setNameMapper(new NameMapper() {

        @Override
        public String map(String name) {
            return name + ":suffix:";
        }

        @Override
        public String unmap(String name) {
            return name.replace(":suffix:", "");
        }
    }).setConnectionMinimumIdleSize(3).setConnectionPoolSize(3).setAddress(RedisRunner.getDefaultRedisServerBindAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    LocalCachedMapOptions<String, Integer> options = LocalCachedMapOptions.<String, Integer>defaults().evictionPolicy(EvictionPolicy.LFU).cacheSize(5);
    RLocalCachedMap<String, Integer> map1 = redisson.getLocalCachedMap("test", options);
    Map<String, Integer> cache1 = map1.getCachedMap();
    RLocalCachedMap<String, Integer> map2 = redisson.getLocalCachedMap("test", options);
    Map<String, Integer> cache2 = map2.getCachedMap();
    assertThat(map1.getName()).isEqualTo("test");
    assertThat(map2.getName()).isEqualTo("test");
    map1.put("1", 1);
    map1.put("2", 2);
    assertThat(map2.get("1")).isEqualTo(1);
    assertThat(map2.get("2")).isEqualTo(2);
    assertThat(cache1.size()).isEqualTo(2);
    assertThat(cache2.size()).isEqualTo(2);
    map1.put("1", 3);
    map2.put("2", 4);
    Thread.sleep(50);
    assertThat(redisson.getKeys().getKeys()).containsOnly("test:suffix:");
    RedisClientConfig destinationCfg = new RedisClientConfig();
    destinationCfg.setAddress(RedisRunner.getDefaultRedisServerBindAddressAndPort());
    RedisClient client = RedisClient.create(destinationCfg);
    RedisConnection destinationConnection = client.connect();
    List<String> channels = destinationConnection.sync(RedisCommands.PUBSUB_CHANNELS);
    assertThat(channels).contains("{test:suffix:}:topic");
    client.shutdown();
    assertThat(cache1.size()).isEqualTo(1);
    assertThat(cache2.size()).isEqualTo(1);
    redisson.shutdown();
}
Also used : RedisClient(org.redisson.client.RedisClient) Config(org.redisson.config.Config) RedisClientConfig(org.redisson.client.RedisClientConfig) RedisClientConfig(org.redisson.client.RedisClientConfig) RedisConnection(org.redisson.client.RedisConnection) Test(org.junit.jupiter.api.Test)

Example 3 with RedisClientConfig

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

the class RedissonTopicTest method testResubscriptionAfterFailover.

@Test
public void testResubscriptionAfterFailover() throws Exception {
    RedisRunner.RedisProcess master = new RedisRunner().nosave().randomDir().port(6400).run();
    RedisRunner.RedisProcess slave1 = new RedisRunner().port(6380).nosave().randomDir().slaveof("127.0.0.1", 6400).run();
    RedisRunner.RedisProcess sentinel1 = new RedisRunner().nosave().randomDir().port(26379).sentinel().sentinelMonitor("myMaster", "127.0.0.1", 6400, 2).sentinelDownAfterMilliseconds("myMaster", 750).sentinelFailoverTimeout("myMaster", 1250).run();
    RedisRunner.RedisProcess sentinel2 = new RedisRunner().nosave().randomDir().port(26380).sentinel().sentinelMonitor("myMaster", "127.0.0.1", 6400, 2).sentinelDownAfterMilliseconds("myMaster", 750).sentinelFailoverTimeout("myMaster", 1250).run();
    RedisRunner.RedisProcess sentinel3 = new RedisRunner().nosave().randomDir().port(26381).sentinel().sentinelMonitor("myMaster", "127.0.0.1", 6400, 2).sentinelDownAfterMilliseconds("myMaster", 750).sentinelFailoverTimeout("myMaster", 1250).run();
    Thread.sleep(1000);
    Config config = new Config();
    config.useSentinelServers().addSentinelAddress(sentinel3.getRedisServerAddressAndPort()).setMasterName("myMaster").setSubscriptionsPerConnection(20).setSubscriptionConnectionPoolSize(200);
    RedissonClient redisson = Redisson.create(config);
    ScheduledExecutorService executor1 = Executors.newScheduledThreadPool(5);
    AtomicBoolean exceptionDetected = new AtomicBoolean(false);
    Deque<String> status = new ConcurrentLinkedDeque<>();
    Runnable rLockPayload = () -> {
        try {
            Integer randomLock = ThreadLocalRandom.current().nextInt(100);
            RLock lock = redisson.getLock(randomLock.toString());
            lock.lock(10, TimeUnit.SECONDS);
            lock.unlock();
            status.add("ok");
        } catch (Exception e) {
            status.add("failed");
            if (e.getCause().getMessage().contains("slaves were synced")) {
                return;
            }
            e.printStackTrace();
            exceptionDetected.set(true);
        }
    };
    executor1.scheduleAtFixedRate(rLockPayload, 100, 50, TimeUnit.MILLISECONDS);
    executor1.scheduleAtFixedRate(rLockPayload, 100, 50, TimeUnit.MILLISECONDS);
    executor1.scheduleAtFixedRate(rLockPayload, 100, 50, TimeUnit.MILLISECONDS);
    executor1.scheduleAtFixedRate(rLockPayload, 100, 50, TimeUnit.MILLISECONDS);
    executor1.scheduleAtFixedRate(rLockPayload, 100, 50, TimeUnit.MILLISECONDS);
    Thread.sleep(java.time.Duration.ofSeconds(10).toMillis());
    RedisClientConfig masterConfig = new RedisClientConfig().setAddress(master.getRedisServerAddressAndPort());
    // Failover from master to slave
    try {
        RedisClient.create(masterConfig).connect().sync(new RedisStrictCommand<Void>("DEBUG", "SEGFAULT"));
    } catch (RedisTimeoutException e) {
    // node goes down, so this command times out waiting for the response
    }
    // Re-introduce master as slave like kubernetes would do
    RedisRunner.RedisProcess slave2 = new RedisRunner().port(6381).nosave().randomDir().slaveof("127.0.0.1", 6380).run();
    System.out.println("Failover Finished, start to see Subscribe timeouts now. Can't recover this without a refresh of redison client ");
    Thread.sleep(java.time.Duration.ofSeconds(10).toMillis());
    assertThat(exceptionDetected.get()).isFalse();
    assertThat(status.peekLast()).isEqualTo("ok");
    executor1.shutdown();
    redisson.shutdown();
    sentinel1.stop();
    sentinel2.stop();
    sentinel3.stop();
    master.stop();
    slave1.stop();
    slave2.stop();
}
Also used : Config(org.redisson.config.Config) RedisClientConfig(org.redisson.client.RedisClientConfig) IOException(java.io.IOException) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedisProcess(org.redisson.RedisRunner.RedisProcess) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedisClientConfig(org.redisson.client.RedisClientConfig)

Example 4 with RedisClientConfig

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

the class RedissonTopicTest method testSlotMigrationInCluster.

@Test
public void testSlotMigrationInCluster() throws Exception {
    RedisRunner master1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master3 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slot1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slot2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slot3 = new RedisRunner().randomPort().randomDir().nosave();
    ClusterRunner clusterRunner = new ClusterRunner().addNode(master1, slot1).addNode(master2, slot2).addNode(master3, slot3);
    ClusterProcesses process = clusterRunner.run();
    Config config = new Config();
    config.useClusterServers().setScanInterval(1000).setSubscriptionMode(SubscriptionMode.MASTER).addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    RedisClientConfig cfg = new RedisClientConfig();
    cfg.setAddress(process.getNodes().iterator().next().getRedisServerAddressAndPort());
    RedisClient c = RedisClient.create(cfg);
    RedisConnection cc = c.connect();
    List<ClusterNodeInfo> mastersList = cc.sync(RedisCommands.CLUSTER_NODES);
    mastersList = mastersList.stream().filter(i -> i.containsFlag(ClusterNodeInfo.Flag.MASTER)).collect(Collectors.toList());
    c.shutdown();
    ClusterNodeInfo destination = mastersList.stream().filter(i -> i.getSlotRanges().iterator().next().getStartSlot() != 10922).findAny().get();
    ClusterNodeInfo source = mastersList.stream().filter(i -> i.getSlotRanges().iterator().next().getStartSlot() == 10922).findAny().get();
    RedisClientConfig sourceCfg = new RedisClientConfig();
    sourceCfg.setAddress(source.getAddress());
    RedisClient sourceClient = RedisClient.create(sourceCfg);
    RedisConnection sourceConnection = sourceClient.connect();
    RedisClientConfig destinationCfg = new RedisClientConfig();
    destinationCfg.setAddress(destination.getAddress());
    RedisClient destinationClient = RedisClient.create(destinationCfg);
    RedisConnection destinationConnection = destinationClient.connect();
    AtomicReference<String> reference = new AtomicReference();
    String channelName = "test{kaO}";
    RTopic topic = redisson.getTopic(channelName);
    topic.addListener(String.class, (ch, m) -> {
        reference.set(m);
    });
    List<String> destList = destinationConnection.sync(RedisCommands.PUBSUB_CHANNELS);
    assertThat(destList).isEmpty();
    List<String> sourceList = sourceConnection.sync(RedisCommands.PUBSUB_CHANNELS);
    assertThat(sourceList).containsOnly(channelName);
    destinationConnection.sync(RedisCommands.CLUSTER_SETSLOT, source.getSlotRanges().iterator().next().getStartSlot(), "IMPORTING", source.getNodeId());
    sourceConnection.sync(RedisCommands.CLUSTER_SETSLOT, source.getSlotRanges().iterator().next().getStartSlot(), "MIGRATING", destination.getNodeId());
    List<String> keys = sourceConnection.sync(RedisCommands.CLUSTER_GETKEYSINSLOT, source.getSlotRanges().iterator().next().getStartSlot(), 100);
    List<Object> params = new ArrayList<Object>();
    params.add(destination.getAddress().getHost());
    params.add(destination.getAddress().getPort());
    params.add("");
    params.add(0);
    params.add(2000);
    params.add("KEYS");
    params.addAll(keys);
    sourceConnection.async(RedisCommands.MIGRATE, params.toArray());
    for (ClusterNodeInfo node : mastersList) {
        RedisClientConfig cc1 = new RedisClientConfig();
        cc1.setAddress(node.getAddress());
        RedisClient ccc = RedisClient.create(cc1);
        RedisConnection connection = ccc.connect();
        connection.sync(RedisCommands.CLUSTER_SETSLOT, source.getSlotRanges().iterator().next().getStartSlot(), "NODE", destination.getNodeId());
        ccc.shutdownAsync();
    }
    Thread.sleep(2000);
    topic.publish("mymessage");
    Awaitility.waitAtMost(Duration.ofSeconds(1)).until(() -> reference.get().equals("mymessage"));
    List<String> destList2 = destinationConnection.sync(RedisCommands.PUBSUB_CHANNELS);
    assertThat(destList2).containsOnly(channelName);
    List<String> sourceList2 = sourceConnection.sync(RedisCommands.PUBSUB_CHANNELS);
    assertThat(sourceList2).isEmpty();
    sourceClient.shutdown();
    destinationClient.shutdown();
    redisson.shutdown();
    process.shutdown();
}
Also used : Config(org.redisson.config.Config) RedisClientConfig(org.redisson.client.RedisClientConfig) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClusterNodeInfo(org.redisson.cluster.ClusterNodeInfo) RedisClient(org.redisson.client.RedisClient) ClusterProcesses(org.redisson.ClusterRunner.ClusterProcesses) RedisClientConfig(org.redisson.client.RedisClientConfig) RedisConnection(org.redisson.client.RedisConnection)

Aggregations

RedisClientConfig (org.redisson.client.RedisClientConfig)4 Config (org.redisson.config.Config)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 RedisClient (org.redisson.client.RedisClient)2 RedisConnection (org.redisson.client.RedisConnection)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Test (org.junit.jupiter.api.Test)1 ClusterProcesses (org.redisson.ClusterRunner.ClusterProcesses)1 RedisProcess (org.redisson.RedisRunner.RedisProcess)1 RFuture (org.redisson.api.RFuture)1 RedisLoadingException (org.redisson.client.RedisLoadingException)1 RedisTimeoutException (org.redisson.client.RedisTimeoutException)1 ClusterNodeInfo (org.redisson.cluster.ClusterNodeInfo)1