沃梦达 / IT编程 / 数据库 / 正文

redis集群删除所有数据

```private static void deleteAllKeys() {JedisCluster jedisCluster = new JedisCluster(new HostAndPort(127.0.0.1, 6379));try {// 获取集群中所有的节点CollectionJedisPool jedisPools = jedisCluster.get...


```
	
	private static void deleteAllKeys() {
		JedisCluster jedisCluster = new JedisCluster(new HostAndPort("127.0.0.1", 6379));
		try {
	                // 获取集群中所有的节点
	                Collection<JedisPool> jedisPools = jedisCluster.getClusterNodes().values();
			boolean isSuccess = false;
			// 遍历所有的节点,获取每个节点上对应数据匹配的结果,并删除
			for (JedisPool pool : jedisPools) {
				Jedis jedis = null;
				try {
					jedis = pool.getResource();
					Set<String> keys = jedis.keys("*");
					Iterator<String> it = keys.iterator();
					while (it.hasNext()) {
						String key = it.next();
						jedis.del(key);
					}
					pool.returnResource(jedis);
					isSuccess = true;
				} catch (JedisMovedDataException ignore) {
					isSuccess = false;
					pool.returnBrokenResource(jedis);
				} catch (Exception e) {
					pool.returnBrokenResource(jedis);
					isSuccess = false;
					System.out.println("Error message: " + e.getMessage());
				}
			}
			if (isSuccess) {
				System.out.println("Complete!");
			} else {
				System.out.println("Error!");
			}
			jedisCluster.close();
		} catch (Exception e) {
			try {
				jedisCluster.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}	}
```

 

本文标题为:redis集群删除所有数据