/** * 注意: * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用 * @return */ @Bean public JedisCluster getJedisCluster() { //获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题) String[] serverArray = redisProperties.getClusterNodes().split(","); Set<HostAndPort> nodes = new HashSet<>(); for (String ipPort : serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim()))); } return new JedisCluster(nodes,10000, 1000,1,redisProperties.getPassword() , new GenericObjectPoolConfig()); }
@Test public void testCalculateConnectionPerSlot() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); jc.set("foo", "bar"); jc.set("test", "test"); assertEquals("bar", node3.get("foo")); assertEquals("test", node2.get("test")); JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); jc2.set("foo", "bar"); jc2.set("test", "test"); assertEquals("bar", node3.get("foo")); assertEquals("test", node2.get("test")); }
@Test public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() throws InterruptedException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); int slot51 = JedisClusterCRC16.getSlot("51"); jc.set("51", "foo"); // node2 is responsible of taking care of slot51 (7186) node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); assertEquals("foo", jc.get("51")); node3.clusterSetSlotStable(slot51); assertEquals("foo", jc.get("51")); node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); // assertEquals("foo", jc.get("51")); // it leads Max Redirections node2.clusterSetSlotStable(slot51); assertEquals("foo", jc.get("51")); }
@Bean//bean public JedisCluster getJedisCluster() { //解析字符串 Set<HostAndPort> nodes = new HashSet<>(); try { String[] cNodes = clusterNodes.split(","); for (String cNode : cNodes) { //192.168.123.1:7001 String[] hp = cNode.split(":"); nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1]))); } return new JedisCluster(nodes); } catch (ArrayIndexOutOfBoundsException | PatternSyntaxException | NullPointerException e) { e.printStackTrace(); } return null; }
/** * This method is called by PDI during transformation startup. * * @param smi step meta interface implementation, containing the step settings * @param sdi step data interface implementation, used to store runtime information * * @return true if initialization completed successfully, false if there was an error preventing the step from working. * */ public boolean init(StepMetaInterface smi, StepDataInterface sdi) { // Casting to step-specific implementation classes is safe RedisOutputStepMeta meta = (RedisOutputStepMeta) smi; RedisOutputStepData data = (RedisOutputStepData) sdi; String url = environmentSubstitute(meta.getUrl()); logBasic("creating redis session factory, addresses=" + url); if (url == null || url.isEmpty()) { throw new IllegalArgumentException("redis cluster url set configured"); } String[] redisNodes = url.split(","); Set<HostAndPort> jedisClusterNodes = new HashSet<>(); try { for (String redisNode: redisNodes) { String[] config = redisNode.split(":"); jedisClusterNodes.add(new HostAndPort(config[0], Integer.parseInt(config[1]))); } } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("redis cluster url not configured correctly"); } client = new JedisCluster(jedisClusterNodes, REDIS_TIMEOUT, new GenericObjectPoolConfig()); return super.init(meta, data); }
@Bean public JedisCluster getJedisCluster() { List<String> serverArray = redisProperties.getNodes(); Set<HostAndPort> nodes = new HashSet<>(); for (String ipPort : serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim()))); } JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(500); config.setMaxIdle(1000 * 60); config.setMaxWaitMillis(1000 * 10); config.setTestOnBorrow(true); return new JedisCluster(nodes, config); }
private ScanPage exist(String cluster, ScanPage scanPage) throws Exception { scanPage.setHasMore(false); List<D_RedisClusterNode> nodes = clusterNodeService.getAllClusterNodes(cluster); Set<HostAndPort> masters = new HashSet<HostAndPort>(); nodes.forEach(node->{ masters.add(new HostAndPort(node.getHost(), node.getPort())); }); JedisCluster jedis = new JedisCluster(masters); try { if(jedis.exists(scanPage.getQuery())){ scanPage.setKeys(new HashSet<String>()); scanPage.getKeys().add(scanPage.getQuery()); } } finally { jedis.close(); } return scanPage; }
/**测试redis集群方案*/ @Test public void testCluster(){ Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); //Jedis Cluster will attempt to discover cluster nodes automatically jedisClusterNodes.add(new HostAndPort("192.168.12.90", 7001)); JedisCluster jc = new JedisCluster(jedisClusterNodes); jc.set("foo", "bar"); String value = jc.get("foo"); System.out.println(value); try { jc.close(); } catch (Exception e) { e.printStackTrace(); } }
@Bean public JedisCluster getRedisCluster(){ Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes1"), Integer.parseInt(environment.getProperty("redis.cluster.port1")))); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes2"), Integer.parseInt(environment.getProperty("redis.cluster.port2")))); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes3"), Integer.parseInt(environment.getProperty("redis.cluster.port3")))); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes4"), Integer.parseInt(environment.getProperty("redis.cluster.port4")))); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes5"), Integer.parseInt(environment.getProperty("redis.cluster.port5")))); jedisClusterNode.add(new HostAndPort(environment.getProperty("redis.cluster.nodes6"), Integer.parseInt(environment.getProperty("redis.cluster.port6")))); JedisPoolConfig cfg = new JedisPoolConfig(); cfg.setMaxTotal(Integer.parseInt(environment.getProperty("redis.cluster.config.max-total"))); cfg.setMaxIdle(Integer.parseInt(environment.getProperty("redis.cluster.config.max-idle"))); cfg.setMaxWaitMillis(Integer.parseInt(environment.getProperty("redis.cluster.config.max-waitmillis"))); cfg.setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("redis.cluster.config.onborrow"))); JedisCluster jc = new JedisCluster(jedisClusterNode, Integer.parseInt(environment.getProperty("redis.cluster.timeout")), Integer.parseInt(environment.getProperty("redis.cluster.max-redirections")), cfg); return jc; }
public RedisDelayQueue(String redisKeyPrefix, String queueName, JedisCluster jedisCluster, int unackTime, DelayQueueProcessListener delayQueueProcessListener) { om = new ObjectMapper(); om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); om.setSerializationInclusion(Include.NON_NULL); om.setSerializationInclusion(Include.NON_EMPTY); om.disable(SerializationFeature.INDENT_OUTPUT); this.redisKeyPrefix = redisKeyPrefix; this.messageStoreKey = redisKeyPrefix + ".MESSAGE." + queueName; this.unackTime = unackTime; this.jedisCluster = jedisCluster; realQueueName = redisKeyPrefix + ".QUEUE." + queueName; this.delayQueueProcessListener = delayQueueProcessListener; }
@Override public boolean stop() { // 清除出集群集合 JedisCluster removeRedisCluster = RedisCluster.removeCache(clusterName); // 关闭集群链接 try { removeRedisCluster.close(); } catch (IOException e) { logger.error(e.getMessage()); } return false; }
@PostConstruct public void init(){ Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); String[] split = redisClusterConfig.getJedisClusterNodesIps().split(";"); for(String one:split){ String[] ipPort = one.split(":"); jedisClusterNodes.add(new HostAndPort(ipPort[0], Integer.valueOf(ipPort[1]))); } GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxIdle(redisClusterConfig.getMaxIdle()); poolConfig.setMaxTotal(redisClusterConfig.getMaxTotal()); poolConfig.setMaxWaitMillis(redisClusterConfig.getMaxWaitMillis()); // poolConfig.setMinIdle(minIdle); poolConfig.setTestOnBorrow(redisClusterConfig.isTestOnBorrow()); poolConfig.setTestOnReturn(redisClusterConfig.isTestOnReturn()); jc = new JedisCluster(jedisClusterNodes,60000,10,poolConfig); }
void setJedisPool() { final String clusters = this.redisConfig.getClusters(); if (StringUtils.isBlank(clusters)) { throw new IllegalArgumentException("redis.clusters must not be blank"); } final int connectionTimeout = this.redisConfig.getConnectionTimeout(); final int soTimeout = this.redisConfig.getSoTimeout(); final int maxRedirections = this.redisConfig.getMaxRedirections(); Set<HostAndPort> nodes = new HashSet<HostAndPort>(); for (String str : clusters.split("[,\\s\\t]+")) { final String[] arr = str.split(":"); nodes.add(new HostAndPort(arr[0], Integer.parseInt(arr[1]))); } this.jedisCluster = new JedisCluster(nodes, connectionTimeout, soTimeout, maxRedirections, this.poolConfig); if (logger.isInfoEnabled()) { logger.info("connect to Redis Cluster {}", clusters); } }
@Test public void test() throws Exception { Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); jedisClusterNodes.add(new HostAndPort(RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT)); RedisClusterConnPool pool = new RedisClusterConnPool(jedisClusterNodes); JedisCluster cluster = pool.getConnection(); Assert.assertNotNull(cluster); pool.returnConnection(cluster); pool.invalidateConnection(cluster); Properties properties = new Properties(); properties.setProperty(RedisConfig.CLUSTER_PROPERTY, RedisConfig.DEFAULT_HOST + ":" + RedisConfig.DEFAULT_PORT); pool = new RedisClusterConnPool(properties); cluster = pool.getConnection(); Assert.assertNotNull(cluster); pool.close(); pool = new RedisClusterConnPool(new PoolConfig(), jedisClusterNodes); pool.close(); }
public JedisCluster appendJedisCluster(RedisConfig conf) { Assert.notNull(conf); Assert.hasLength(conf.getRedisType()); if(conf.getCluster() != null && conf.getCluster()) { if(!jedisClusterPool.containsKey(conf.getRedisType())) { redisConfigs.put(conf.getRedisType(), conf); final JedisCluster cluster; jedisClusterPool.put(conf.getRedisType(), cluster = createJedisClusterPool(conf)); bindGlobal(conf); return cluster; } } throw new RedisClientException("Can't append JedisCluster, this is a redis sharded config"); }
/** * Store a job in Redis * * @param jobDetail the {@link JobDetail} object to be stored * @param replaceExisting if true, any existing job with the same group and name as the given job will be overwritten * @param jedis a thread-safe Redis connection * @throws ObjectAlreadyExistsException */ @Override @SuppressWarnings("unchecked") public void storeJob(JobDetail jobDetail, boolean replaceExisting, JedisCluster jedis) throws ObjectAlreadyExistsException { final String jobHashKey = redisSchema.jobHashKey(jobDetail.getKey()); final String jobDataMapHashKey = redisSchema.jobDataMapHashKey(jobDetail.getKey()); final String jobGroupSetKey = redisSchema.jobGroupSetKey(jobDetail.getKey()); if (!replaceExisting && jedis.exists(jobHashKey)) { throw new ObjectAlreadyExistsException(jobDetail); } jedis.hmset(jobHashKey, (Map<String, String>) mapper.convertValue(jobDetail, new TypeReference<HashMap<String, String>>() { })); if (jobDetail.getJobDataMap() != null && !jobDetail.getJobDataMap().isEmpty()) { jedis.hmset(jobDataMapHashKey, getStringDataMap(jobDetail.getJobDataMap())); } jedis.sadd(redisSchema.jobsSet(), jobHashKey); jedis.sadd(redisSchema.jobGroupsSet(), jobGroupSetKey); jedis.sadd(jobGroupSetKey, jobHashKey); }
/** * Unsets the state of the given trigger key by removing the trigger from all trigger state sets. * * @param triggerHashKey the redis key of the desired trigger hash * @param jedis a thread-safe Redis connection * @return true if the trigger was removed, false if the trigger was stateless * @throws JobPersistenceException if the unset operation failed */ @Override public boolean unsetTriggerState(String triggerHashKey, JedisCluster jedis) throws JobPersistenceException { boolean removed = false; List<Long> responses = new ArrayList<>(RedisTriggerState.values().length); for (RedisTriggerState state : RedisTriggerState.values()) { responses.add(jedis.zrem(redisSchema.triggerStateKey(state), triggerHashKey)); } for (Long response : responses) { removed = response == 1; if (removed) { jedis.del(redisSchema.triggerLockKey(redisSchema.triggerKey(triggerHashKey))); break; } } return removed; }
/** * Pause the trigger with the given key * * @param triggerKey the key of the trigger to be paused * @param jedis a thread-safe Redis connection * @throws JobPersistenceException if the desired trigger does not exist */ @Override public void pauseTrigger(TriggerKey triggerKey, JedisCluster jedis) throws JobPersistenceException { final String triggerHashKey = redisSchema.triggerHashKey(triggerKey); Boolean exists = jedis.exists(triggerHashKey); Double completedScore = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.COMPLETED), triggerHashKey); String nextFireTimeResponse = jedis.hget(triggerHashKey, TRIGGER_NEXT_FIRE_TIME); Double blockedScore = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.BLOCKED), triggerHashKey); if (!exists) { return; } if (completedScore != null) { // doesn't make sense to pause a completed trigger return; } final long nextFireTime = nextFireTimeResponse == null || nextFireTimeResponse.isEmpty() ? -1 : Long.parseLong(nextFireTimeResponse); if (blockedScore != null) { setTriggerState(RedisTriggerState.PAUSED_BLOCKED, (double) nextFireTime, triggerHashKey, jedis); } else { setTriggerState(RedisTriggerState.PAUSED, (double) nextFireTime, triggerHashKey, jedis); } }
@Override public void afterPropertiesSet() throws Exception { if (jedisClusterNodes == null || jedisClusterNodes.size() == 0) { logger.error("jedisClusterNodes is null."); throw new NullPointerException("jedisClusterNodes is null."); } Set<HostAndPort> haps = new HashSet<>(); for (String node : jedisClusterNodes) { String[] arr = node.split(COLON); if (arr.length != 2) { logger.error("node address error!"); throw new ParseException("node address error!", node.length() - 1); } haps.add(new HostAndPort(arr[0], Integer.valueOf(arr[1]))); } jedisCluster = new JedisCluster(haps, connectionTimeout, soTimeout, maxRedirections, genericObjectPoolConfig); }
public void create() { try { LOG.debug("Starting RedisClusterProvider ... configuration:" + getRedisConfiguration()); JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(1000); poolConfig.setMinIdle(2); pool = new JedisCluster(hosts(getRedisConfiguration().getServers()), poolConfig); testConnection(); LOG.debug("RedisClusterProvider started."); } catch (Exception e) { LOG.error("Failed to start RedisClusterProvider."); throw new IllegalStateException("Error starting RedisClusterProvider", e); } }
@SuppressWarnings("resource") public static void main(String[] args) { Set<HostAndPort> nodes = new HashSet<HostAndPort>(); nodes.add(new HostAndPort("127.0.0.1", 7000)); nodes.add(new HostAndPort("127.0.0.1", 7001)); nodes.add(new HostAndPort("127.0.0.1", 7002)); nodes.add(new HostAndPort("127.0.0.1", 7003)); nodes.add(new HostAndPort("127.0.0.1", 7004)); nodes.add(new HostAndPort("127.0.0.1", 7005)); JedisCluster cluster = new JedisCluster(nodes, 5000); System.out.println(cluster.get("foo")); cluster.set("test", "6379"); System.out.println(cluster.get("test")); Map<String, String> inviteePhone = new HashMap<String, String>(); inviteePhone.put("inviterID", "1001"); inviteePhone.put("status", "0"); cluster.hmset("inviteePhone", inviteePhone); System.out.println(cluster.hget("inviteePhone", "inviterID")); System.out.println(cluster.hget("inviteePhone", "status")); }
@Bean public JedisCluster jedisCluster(JedisPoolConfig jedisPoolConfig){ Set<HostAndPort> sets=new HashSet<>(); for (String node:clusterNodes){ String host=node.split(":")[0]; int port=Integer.valueOf(node.split(":")[1]); sets.add(new HostAndPort(host,port)); } Assert.notNull(sets, "jedisClusterNode object must not be null"); return new JedisCluster(sets,this.clusterTimeout, this.clusterMaxAttempts,jedisPoolConfig); }
public static void main(String[] args) { //加载服务列表 Set<HostAndPort> redisClusterNodes =new HashSet<>(); redisClusterNodes.add(new HostAndPort("192.168.137.147",7001)); redisClusterNodes.add(new HostAndPort("192.168.137.147",7002)); redisClusterNodes.add(new HostAndPort("192.168.137.147",7003)); redisClusterNodes.add(new HostAndPort("192.168.137.147",7004)); redisClusterNodes.add(new HostAndPort("192.168.137.147",7005)); redisClusterNodes.add(new HostAndPort("192.168.137.147",7006)); //redis配置 JedisPoolConfig jedisPoolConfig=new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(100); jedisPoolConfig.setMaxIdle(20); jedisPoolConfig.setMaxWaitMillis(-1); jedisPoolConfig.setTestOnBorrow(true); //redis集群 JedisCluster jedisCluster=new JedisCluster(redisClusterNodes,6000,1000,jedisPoolConfig); PrinterUtils.printELog(jedisCluster.set("username","tom")); PrinterUtils.printELog(jedisCluster.set("age","23")); PrinterUtils.printILog(jedisCluster.get("username")); PrinterUtils.printILog(jedisCluster.get("age")); PrinterUtils.printILog(jedisCluster.get("age")); PrinterUtils.printILog(jedisCluster.get("username")); PrinterUtils.printILog(jedisCluster.get("password")); PrinterUtils.printILog(jedisCluster.getClusterNodes()); try { jedisCluster.close(); } catch (IOException e) { e.printStackTrace(); } }
@After public void tearDown() { // clear all slots int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { slotsToDelete[i] = i; } node1.clusterDelSlots(slotsToDelete); node2.clusterDelSlots(slotsToDelete); node3.clusterDelSlots(slotsToDelete); }
@Test public void testDiscoverNodesAutomatically() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); assertEquals(3, jc.getClusterNodes().size()); JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); assertEquals(3, jc2.getClusterNodes().size()); }
@Test public void testRecalculateSlotsWhenMoved() throws InterruptedException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); int slot51 = JedisClusterCRC16.getSlot("51"); node2.clusterDelSlots(slot51); node3.clusterDelSlots(slot51); node3.clusterAddSlots(slot51); JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); }
@Test public void testAskResponse() throws InterruptedException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); int slot51 = JedisClusterCRC16.getSlot("51"); node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); }
@Test(expected = JedisClusterMaxRedirectionsException.class) public void testRedisClusterMaxRedirections() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); int slot51 = JedisClusterCRC16.getSlot("51"); // This will cause an infinite redirection loop node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); jc.set("51", "foo"); }
@Test public void testClusterCountKeysInSlot() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); for (int index = 0; index < 5; index++) { jc.set("foo{bar}" + index, "hello"); } int slot = JedisClusterCRC16.getSlot("foo{bar}"); assertEquals(DEFAULT_REDIRECTIONS, node1.clusterCountKeysInSlot(slot).intValue()); }
@Test(expected = JedisException.class) public void testIfPoolConfigAppliesToClusterPools() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(0); config.setMaxWaitMillis(DEFAULT_TIMEOUT); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config); jc.set("52", "poolTestValue"); }
@Test public void testJedisClusterTimeout() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); for (JedisPool pool : jc.getClusterNodes().values()) { Jedis jedis = pool.getResource(); assertEquals(jedis.getClient().getConnectionTimeout(), 4000); assertEquals(jedis.getClient().getSoTimeout(), 4000); jedis.close(); } }
@Test public void testJedisClusterRunsWithMultithreaded() throws InterruptedException, ExecutionException, IOException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); jc.set("foo", "bar"); ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); List<Future<String>> futures = new ArrayList<Future<String>>(); for (int i = 0; i < 50; i++) { executor.submit(new Callable<String>() { @Override public String call() throws Exception { // FIXME : invalidate slot cache from JedisCluster to test // random connection also does work return jc.get("foo"); } }); } for (Future<String> future : futures) { String value = future.get(); assertEquals("bar", value); } jc.close(); }
@Test(timeout = DEFAULT_TIMEOUT) public void testReturnConnectionOnJedisConnectionException() throws InterruptedException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisPoolConfig config = DEFAULT_CONFIG; config.setMaxTotal(1); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config); Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource(); ClientKillerUtil.tagClient(j, "DEAD"); ClientKillerUtil.killClient(j, "DEAD"); j.close(); jc.get("test"); }
@Test(expected = JedisClusterMaxRedirectionsException.class, timeout = DEFAULT_TIMEOUT) public void testReturnConnectionOnRedirection() { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisPoolConfig config = DEFAULT_CONFIG; config.setMaxTotal(1); JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster", config); // This will cause an infinite redirection between node 2 and 3 node3.clusterSetSlotMigrating(15363, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); jc.get("e"); }
@Test public void testLocalhostNodeNotAddedWhen127Present() { HostAndPort localhost = new HostAndPort("localhost", 7379); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); // cluster node is defined as 127.0.0.1; adding localhost should work, // but shouldn't show up. jedisClusterNode.add(localhost); JedisPoolConfig config = DEFAULT_CONFIG; config.setMaxTotal(1); JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG); Map<String, JedisPool> clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost))); }
@Test public void testInvalidStartNodeNotAdded() { HostAndPort invalidHost = new HostAndPort("not-a-real-host", 7379); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); jedisClusterNode.add(invalidHost); JedisPoolConfig config = DEFAULT_CONFIG; config.setMaxTotal(1); JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster", config); Map<String, JedisPool> clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost))); }
@Bean public JedisCluster jedisClusterFactory() { String[] serverArray = redisProperties.getNodes().split(","); Set<HostAndPort> nodes = new HashSet<>(); for (String ipPort: serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim()))); } return new JedisCluster(nodes, redisProperties.getCommandTimeout()); }
@Bean public JedisCluster jedisClusterFactory() { String[] serverArray = redisProperties.getNodes().split(","); Set<HostAndPort> nodes = new HashSet<HostAndPort>(); for (String ipPort: serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim()))); } return new JedisCluster(nodes, redisProperties.getCommandTimeout()); }