org.redisson.api.RedissonClient Java Examples

The following examples show how to use org.redisson.api.RedissonClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedissonReferenceReactiveTest.java    From redisson with Apache License 2.0 8 votes vote down vote up
@Test
public void testReactiveToNormal() throws InterruptedException {
    RBatchReactive batch = redisson.createBatch(BatchOptions.defaults());
    RBucketReactive<Object> b1 = batch.getBucket("b1");
    RBucketReactive<Object> b2 = batch.getBucket("b2");
    RBucketReactive<Object> b3 = batch.getBucket("b3");
    b2.set(b3);
    b1.set(b2);
    b3.set(b1);
    sync(batch.execute());

    RedissonClient lredisson = Redisson.create(redisson.getConfig());
    RBatch b = lredisson.createBatch(BatchOptions.defaults());
    b.getBucket("b1").getAsync();
    b.getBucket("b2").getAsync();
    b.getBucket("b3").getAsync();
    List<RBucket> result = (List<RBucket>)b.execute().getResponses();
    assertEquals("b2", result.get(0).getName());
    assertEquals("b3", result.get(1).getName());
    assertEquals("b1", result.get(2).getName());

    lredisson.shutdown();
}
 
Example #2
Source File: RedisConfig.java    From earth-frost with Apache License 2.0 6 votes vote down vote up
/**
 * 哨兵模式
 *
 * @param redissonProperties redisson配置
 * @return client
 */
static RedissonClient redissonUseSentinelServers(RedissonProperties redissonProperties) {
  Config config = new Config();
  SentinelServersConfig serverConfig = config.useSentinelServers()
      .addSentinelAddress(redissonProperties.getSentinelAddresses())
      .setTimeout(redissonProperties.getTimeout())
      .setScanInterval(redissonProperties.getScanInterval())
      .setMasterName(redissonProperties.getMasterName())
      .setSlaveConnectionPoolSize(redissonProperties.getSlaveConnectionPoolSize())
      .setMasterConnectionPoolSize(redissonProperties.getMasterConnectionPoolSize());
  if (redissonProperties.getPassword() != null && redissonProperties.getPassword().length() > 0) {
    serverConfig.setPassword(redissonProperties.getPassword());
  }

  return Redisson.create(config);
}
 
Example #3
Source File: RedissonRegionFactory.java    From redisson with Apache License 2.0 6 votes vote down vote up
protected RedissonClient createRedissonClient(Properties properties) {
    Config config = null;
    if (!properties.containsKey(REDISSON_CONFIG_PATH)) {
        config = loadConfig(RedissonRegionFactory.class.getClassLoader(), "redisson.json");
        if (config == null) {
            config = loadConfig(RedissonRegionFactory.class.getClassLoader(), "redisson.yaml");
        }
    } else {
        String configPath = ConfigurationHelper.getString(REDISSON_CONFIG_PATH, properties);
        config = loadConfig(RedissonRegionFactory.class.getClassLoader(), configPath);
        if (config == null) {
            config = loadConfig(configPath);
        }
    }
    
    if (config == null) {
        throw new CacheException("Unable to locate Redisson configuration");
    }
    
    return Redisson.create(config);
}
 
Example #4
Source File: RedissonBoundedBlockingQueueTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPollWithBrokenConnection() throws IOException, InterruptedException, ExecutionException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .randomPort()
            .run();
    
    Config config = new Config();
    config.useSingleServer().setAddress(runner.getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("bounded-queue:pollTimeout");
    assertThat(queue1.trySetCapacity(5)).isTrue();
    RFuture<Integer> f = queue1.pollAsync(5, TimeUnit.SECONDS);
    
    Assert.assertFalse(f.await(1, TimeUnit.SECONDS));
    runner.stop();

    long start = System.currentTimeMillis();
    assertThat(f.get()).isNull();
    assertThat(System.currentTimeMillis() - start).isGreaterThan(3800);
    
    redisson.shutdown();
}
 
Example #5
Source File: BucketExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    RedissonClient redisson = Redisson.create();
    
    RBucket<String> bucket = redisson.getBucket("test");
    bucket.set("123");
    boolean isUpdated = bucket.compareAndSet("123", "4934");
    String prevObject = bucket.getAndSet("321");
    boolean isSet = bucket.trySet("901");
    long objectSize = bucket.size();
    
    // set with expiration
    bucket.set("value", 10, TimeUnit.SECONDS);
    boolean isNewSet = bucket.trySet("nextValue", 10, TimeUnit.SECONDS);
    
    redisson.shutdown();
}
 
Example #6
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSyncCommands() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic = redisson.getTopic("system_bus");
    RSet<String> redissonSet = redisson.getSet("set1");
    CountDownLatch latch = new CountDownLatch(1);
    topic.addListener(String.class, (channel, msg) -> {
        for (int j = 0; j < 1000; j++) {
            redissonSet.contains("" + j);
        }
        latch.countDown();
    });
    
    topic.publish("sometext");
    
    latch.await();
    redisson.shutdown();
}
 
Example #7
Source File: RemoteServiceExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient server = Redisson.create();
    RedissonClient client = Redisson.create();
    try {
        server.getRemoteService().register(RemoteInterface.class, new RemoteImpl());

        RemoteInterface service = client.getRemoteService().get(RemoteInterface.class);

        service.myMethod(21L);

    } finally {
        client.shutdown();
        server.shutdown();
    }

}
 
Example #8
Source File: ExecutorServiceExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    Config config = new Config();
    config.useClusterServers()
        .addNodeAddress("127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003");
    
    RedissonClient redisson = Redisson.create(config);

    RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);
    nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor", 1));
    RedissonNode node = RedissonNode.create(nodeConfig);
    node.start();

    RExecutorService e = redisson.getExecutorService("myExecutor");
    e.execute(new RunnableTask());
    e.submit(new CallableTask());
    
    e.shutdown();
    node.shutdown();
}
 
Example #9
Source File: RedissonBoundedBlockingQueueTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPollAsyncCancel() {
    Config config = createConfig();
    config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1);

    RedissonClient redisson = Redisson.create(config);
    redisson.getKeys().flushall();
    
    RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("queue:pollany");
    assertThat(queue1.trySetCapacity(15)).isTrue();
    for (int i = 0; i < 10; i++) {
        RFuture<Integer> f = queue1.pollAsync(1, TimeUnit.SECONDS);
        f.cancel(true);
    }
    assertThat(queue1.add(1)).isTrue();
    assertThat(queue1.add(2)).isTrue();
    assertThat(queue1.size()).isEqualTo(2);
    
    redisson.shutdown();
}
 
Example #10
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test(expected = WriteRedisConnectionException.class)
public void testRedisFailed() throws IOException, InterruptedException {
    RedisRunner.RedisProcess master = new RedisRunner()
            .port(6377)
            .nosave()
            .randomDir()
            .run();

    Config config = new Config();
    config.useSingleServer().setAddress("redis://127.0.0.1:6377");
    RedissonClient redisson = Redisson.create(config);

    RLock lock = redisson.getLock("myLock");
    // kill RedisServer while main thread is sleeping.
    master.stop();
    Thread.sleep(3000);
    lock.tryLock(5, 10, TimeUnit.SECONDS);
}
 
Example #11
Source File: BucketExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();
    
    RBucket<String> bucket = redisson.getBucket("test");
    bucket.set("123");
    boolean isUpdated = bucket.compareAndSet("123", "4934");
    String prevObject = bucket.getAndSet("321");
    boolean isSet = bucket.trySet("901");
    long objectSize = bucket.size();
    
    // set with expiration
    bucket.set("value", 10, TimeUnit.SECONDS);
    boolean isNewSet = bucket.trySet("nextValue", 10, TimeUnit.SECONDS);
    
    redisson.shutdown();
}
 
Example #12
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveByInstance() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic1");
    MessageListener listener = new MessageListener() {
        @Override
        public void onMessage(CharSequence channel, Object msg) {
            Assert.fail();
        }
    };
    
    topic1.addListener(Message.class, listener);

    topic1 = redisson.getTopic("topic1");
    topic1.removeListener(listener);
    topic1.publish(new Message("123"));

    redisson.shutdown();
}
 
Example #13
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
protected Thread sendCommands(RedissonClient redisson, String topicName) {
    Thread t = new Thread() {
        @Override
        public void run() {
            List<RFuture<?>> futures = new ArrayList<RFuture<?>>();
            
            for (int i = 0; i < 100; i++) {
                RFuture<?> f1 = redisson.getBucket("i" + i).getAsync();
                RFuture<?> f2 = redisson.getBucket("i" + i).setAsync("");
                RFuture<?> f3 = redisson.getTopic(topicName).publishAsync(1);
                futures.add(f1);
                futures.add(f2);
                futures.add(f3);
            }
            
            for (RFuture<?> rFuture : futures) {
                rFuture.awaitUninterruptibly();
            }
        };
    };
    t.start();
    return t;
}
 
Example #14
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testInCluster() throws Exception {
    RedisRunner master1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master3 = new RedisRunner().randomPort().randomDir().nosave();

    ClusterRunner clusterRunner = new ClusterRunner()
            .addNode(master1)
            .addNode(master2)
            .addNode(master3);
    ClusterProcesses process = clusterRunner.run();
    
    Config config = new Config();
    config.useClusterServers()
    .addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    
    RReadWriteLock s = redisson.getReadWriteLock("1234");
    s.writeLock().lock();
    s.readLock().lock();
    s.readLock().unlock();
    s.writeLock().unlock();
    
    redisson.shutdown();
    process.shutdown();
}
 
Example #15
Source File: RedissonRedLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testLockSuccess() throws IOException, InterruptedException {
    RedisProcess redis1 = redisTestMultilockInstance();
    RedisProcess redis2 = redisTestMultilockInstance();
    
    RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
    RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
    
    RLock lock1 = client1.getLock("lock1");
    RLock lock2 = client1.getLock("lock2");
    RLock lock3 = client2.getLock("lock3");
    
    testLock(lock1, lock2, lock3, lock1);
    testLock(lock1, lock2, lock3, lock2);
    testLock(lock1, lock2, lock3, lock3);
    
    client1.shutdown();
    client2.shutdown();
    
    assertThat(redis1.stop()).isEqualTo(0);
    assertThat(redis2.stop()).isEqualTo(0);
}
 
Example #16
Source File: RedisInitializer.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * @author kuangyoubo
 * @author fanpan26
 * 优先级
 * 通过名字注入 > 配置文件 > 参数配置 > 默认
 */
private void initRedis() {
    if( redisConfig.useInjectRedissonClient() ) {
        logger.info("Get the RedissonClient through injection, Bean name is \"{}\"", redisConfig.getClientBeanName());

        try {
            redissonClient = applicationContext.getBean(redisConfig.getClientBeanName(), RedissonClient.class);
            return;
        } catch (BeansException e) {
            logger.warn("RedissonClient is not found, Recreate RedissonClient on configuration information.");
        }
    }

    /**
     * 优先级
     * 配置文件 > 参数配置 > 默认
     */
    Config config = getConfigByFile();
    if(config == null) {
        config = redisConfig.useConfigParameter() ? redisConfig.getClusterOrSentinelConfig() : getSingleServerConfig();
    }
    redissonClient = Redisson.create(config);
}
 
Example #17
Source File: BinaryStreamExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();

    RBinaryStream stream = redisson.getBinaryStream("myStream");
    
    byte[] values = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    stream.trySet(values);
    stream.set(values);
    
    InputStream is = stream.getInputStream();
    StringBuilder sb = new StringBuilder();
    int ch;
    while((ch = is.read()) != -1) {
        sb.append((char)ch);
    }
    String str = sb.toString();
    
    OutputStream os = stream.getOutputStream();
    for (int i = 0; i < values.length; i++) {
        byte c = values[i];
        os.write(c);
    }
    
    redisson.shutdown();
}
 
Example #18
Source File: RedissonConfig.java    From dk-foundation with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Bean
@ConditionalOnProperty(name="spring.redis.url")
RedissonClient redissonSingle() {
    Config config = new Config();
    SingleServerConfig serverConfig = config.useSingleServer()
            .setAddress(redisProperties.getUrl())
            .setDatabase(redisProperties.getDatabase());
    if (StringUtils.isNotBlank(redisProperties.getPassword())) {
        serverConfig.setPassword(redisProperties.getPassword());
    }
    if (redisProperties.getTimeout() != null) {
        serverConfig.setTimeout((int) redisProperties.getTimeout().getSeconds());
    }
    if (redisProperties.getJedis().getPool() != null) {
        serverConfig.setConnectionPoolSize(redisProperties.getJedis().getPool().getMaxActive())
                .setConnectionMinimumIdleSize(redisProperties.getJedis().getPool().getMinIdle());
    }

    return Redisson.create(config);
}
 
Example #19
Source File: RedissonTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  final Config config = new Config();
  config.useSingleServer().setAddress("redis://127.0.0.1:6379");

  final RedissonClient redissonClient = Redisson.create(config);
  final RMap<String,String> map = redissonClient.getMap("map");

  map.put("key", "value");
  assertEquals("value", map.get("key"));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  redissonClient.shutdown();
}
 
Example #20
Source File: RedisConfig.java    From earth-frost with Apache License 2.0 6 votes vote down vote up
/**
 * 集群模式
 *
 * @param redissonProperties redisson配置
 * @return client
 */
static RedissonClient redissonCluster(RedissonProperties redissonProperties) {
  Config config = new Config();
  ClusterServersConfig serverConfig = config.useClusterServers()
      .addNodeAddress(redissonProperties.getNodeAddresses())
      .setTimeout(redissonProperties.getTimeout())
      .setScanInterval(redissonProperties.getScanInterval())
      .setSlaveConnectionPoolSize(redissonProperties.getSlaveConnectionPoolSize())
      .setMasterConnectionPoolSize(redissonProperties.getMasterConnectionPoolSize());

  if (redissonProperties.getPassword() != null && redissonProperties.getPassword().length() > 0) {
    serverConfig.setPassword(redissonProperties.getPassword());
  }

  return Redisson.create(config);
}
 
Example #21
Source File: RedisReader.java    From geowave with Apache License 2.0 6 votes vote down vote up
public RedisReader(
    final RedissonClient client,
    final Compression compression,
    final ReaderParams<T> readerParams,
    final String namespace,
    final boolean visibilityEnabled,
    final boolean async) {
  this.iterator =
      createIteratorForReader(
          client,
          compression,
          readerParams,
          readerParams.getRowTransformer(),
          namespace,
          visibilityEnabled,
          false);
}
 
Example #22
Source File: RedisUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static RedisScoredSetWrapper<GeoWaveRedisPersistedRow> getRowSet(
    final RedissonClient client,
    final Compression compression,
    final String setNamePrefix,
    final byte[] partitionKey,
    final boolean requiresTimestamp,
    final boolean visibilityEnabled) {
  return getRowSet(
      client,
      compression,
      getRowSetName(setNamePrefix, partitionKey),
      requiresTimestamp,
      visibilityEnabled);
}
 
Example #23
Source File: RedisUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static RedisMapWrapper getDataIndexMap(
    final RedissonClient client,
    final Serialization serialization,
    final Compression compression,
    final String namespace,
    final String typeName,
    final boolean visibilityEnabled) {
  return new RedisMapWrapper(
      client,
      getRowSetPrefix(namespace, typeName, DataIndexUtils.DATA_ID_INDEX.getName()),
      compression.getCodec(serialization.getCodec()),
      visibilityEnabled);
}
 
Example #24
Source File: RedisConfig.java    From earth-frost with Apache License 2.0 5 votes vote down vote up
static RedissonClient redissonClient(RedissonProperties redissonProperties) {
  switch (redissonProperties.getMode()) {
    case 1:
      return redissonCluster(redissonProperties);
    case 2:
      return redissonReplicatedServers(redissonProperties);
    case 3:
      return redissonUseSentinelServers(redissonProperties);
    case 4:
      return redissonUseMasterSlaveServers(redissonProperties);
    default:
      return redissonSingle(redissonProperties);
  }
}
 
Example #25
Source File: GuavaRedisCache.java    From t-io with Apache License 2.0 5 votes vote down vote up
private static void init(RedissonClient redisson) {
	if (!inited) {
		synchronized (GuavaRedisCache.class) {
			if (!inited) {
				topic = redisson.getTopic(CACHE_CHANGE_TOPIC);
				topic.addListener(CacheChangedVo.class, new MessageListener<CacheChangedVo>() {
					@Override
					public void onMessage(CharSequence channel, CacheChangedVo cacheChangedVo) {
						String clientid = cacheChangedVo.getClientId();
						if (StrUtil.isBlank(clientid)) {
							log.error("clientid is null");
							return;
						}
						if (Objects.equals(CacheChangedVo.CLIENTID, clientid)) {
							log.debug("自己发布的消息,{}", clientid);
							return;
						}

						String cacheName = cacheChangedVo.getCacheName();
						GuavaRedisCache guavaRedisCache = GuavaRedisCache.getCache(cacheName);
						if (guavaRedisCache == null) {
							log.info("不能根据cacheName[{}]找到GuavaRedisCache对象", cacheName);
							return;
						}

						CacheChangeType type = cacheChangedVo.getType();
						if (type == CacheChangeType.PUT || type == CacheChangeType.UPDATE || type == CacheChangeType.REMOVE) {
							String key = cacheChangedVo.getKey();
							guavaRedisCache.guavaCache.remove(key);
						} else if (type == CacheChangeType.CLEAR) {
							guavaRedisCache.guavaCache.clear();
						}
					}
				});
				inited = true;
			}
		}
	}
}
 
Example #26
Source File: ConcurrentRedissonSortedSetTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdd_SingleInstance() throws InterruptedException {
    final String name = "testAdd_SingleInstance";

    RedissonClient r = BaseTest.createInstance();
    RSortedSet<Integer> map = r.getSortedSet(name);
    map.clear();

    int length = 5000;
    final List<Integer> elements = new ArrayList<Integer>();
    for (int i = 1; i < length + 1; i++) {
        elements.add(i);
    }
    Collections.shuffle(elements);
    final AtomicInteger counter = new AtomicInteger(-1);
    testSingleInstanceConcurrency(length, rc -> {
        RSortedSet<Integer> set = rc.getSortedSet(name);
        int c = counter.incrementAndGet();
        Integer element = elements.get(c);
        Assert.assertTrue(set.add(element));
    });

    Collections.sort(elements);
    Integer[] p = elements.toArray(new Integer[elements.size()]);
    assertThat(map).containsExactly(p);

    map.clear();
    r.shutdown();
}
 
Example #27
Source File: RedisReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private CloseableIterator<T> createIterator(
    final RedissonClient client,
    final Compression compression,
    final RangeReaderParams<T> readerParams,
    final GeoWaveRowIteratorTransformer<T> rowTransformer,
    final String namespace,
    final Collection<SinglePartitionQueryRanges> ranges,
    final Set<String> authorizations,
    final boolean visibilityEnabled,
    final boolean async) {
  final Iterator<CloseableIterator> it =
      Arrays.stream(ArrayUtils.toObject(readerParams.getAdapterIds())).map(
          adapterId -> new BatchedRangeRead(
              client,
              compression,
              RedisUtils.getRowSetPrefix(
                  namespace,
                  readerParams.getInternalAdapterStore().getTypeName(adapterId),
                  readerParams.getIndex().getName()),
              adapterId,
              ranges,
              rowTransformer,
              new ClientVisibilityFilter(authorizations),
              DataStoreUtils.isMergingIteratorRequired(readerParams, visibilityEnabled),
              async,
              RedisUtils.isGroupByRowAndIsSortByTime(readerParams, adapterId),
              RedisUtils.isSortByKeyRequired(readerParams),
              visibilityEnabled).results()).iterator();
  final CloseableIterator<T>[] itArray = Iterators.toArray(it, CloseableIterator.class);
  return new CloseableIteratorWrapper<>(new Closeable() {
    AtomicBoolean closed = new AtomicBoolean(false);

    @Override
    public void close() throws IOException {
      if (!closed.getAndSet(true)) {
        Arrays.stream(itArray).forEach(it -> it.close());
      }
    }
  }, Iterators.concat(itArray));
}
 
Example #28
Source File: RedissonBucketsTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInCluster() throws FailedToStartRedisException, IOException, InterruptedException {
    RedisRunner master1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master3 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave3 = new RedisRunner().randomPort().randomDir().nosave();

    ClusterRunner clusterRunner = new ClusterRunner()
            .addNode(master1, slave1)
            .addNode(master2, slave2)
            .addNode(master3, slave3);
    ClusterProcesses process = clusterRunner.run();
    
    Config config = new Config();
    config.useClusterServers()
    .setLoadBalancer(new RandomLoadBalancer())
    .addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    
    int size = 10000;
    Map<String, Integer> map = new HashMap<>();
    for (int i = 0; i < size; i++) {
        map.put("test" + i, i);
        redisson.getBucket("test" + i).set(i);
    }
    
    Set<String> queryKeys = new HashSet<>(map.keySet());
    queryKeys.add("test_invalid");
    Map<String, Integer> buckets = redisson.getBuckets().get(queryKeys.toArray(new String[map.size()]));
    
    assertThat(buckets).isEqualTo(map);
    
    redisson.shutdown();
    process.shutdown();
}
 
Example #29
Source File: TasksRunnerService.java    From redisson with Apache License 2.0 5 votes vote down vote up
public TasksRunnerService(CommandExecutor commandExecutor, RedissonClient redisson, Codec codec, String name, ConcurrentMap<String, ResponseEntry> responses) {
    this.commandExecutor = commandExecutor;
    this.name = name;
    this.redisson = redisson;
    this.responses = responses;
    
    this.codec = codec;
}
 
Example #30
Source File: RedissonPriorityBlockingQueueTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testPollAsyncReattach() throws InterruptedException, IOException, ExecutionException, TimeoutException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .randomPort()
            .run();
    
    Config config = new Config();
    config.useSingleServer().setAddress(runner.getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);
    
    RBlockingQueue<Integer> queue1 = getQueue(redisson);
    RFuture<Integer> f = queue1.pollAsync(10, TimeUnit.SECONDS);
    f.await(1, TimeUnit.SECONDS);
    runner.stop();

    runner = new RedisRunner()
            .port(runner.getRedisServerPort())
            .nosave()
            .randomDir()
            .run();
    queue1.put(123);
    
    // check connection rotation
    for (int i = 0; i < 10; i++) {
        queue1.put(i + 1000);
    }
    Integer result = f.get();
    assertThat(queue1.size()).isEqualTo(10);
    
    assertThat(result).isEqualTo(123);
    
    redisson.shutdown();
    runner.stop();
}