获取Redis里的所有key-value对

时间:2022-11-05 19:18:15

众里寻他千百度,蓦然回首,那人却在,灯火阑珊处。


    public static void main(String[] args) {
long start = System.currentTimeMillis();

//连接redis服务器,localhost:6379
Jedis redis = new Jedis("localhost", 6379);
// 获取所有key
Set<byte[]> keySet = redis.keys("*".getBytes());
byte[][] keys = keySet.toArray(new byte[keySet.size()][]);
// 获取所有value
byte[][] values = redis.mget(keys).toArray(new byte[keySet.size()][]);

// 打印key-value对
for (int i = 0; i < keySet.size(); ++i) {
System.out.println(byte2hex(keys[i]) + " --- " + byte2hex(values[i]));
}

long end = System.currentTimeMillis();
// 计算耗时
System.out.println("Query " + values.length + " pairs takes " + (end - start) + " millis");
redis.close();
}

private static String byte2hex(byte[] buffer) {
String h = "0x";

for (byte aBuffer : buffer) {
String temp = Integer.toHexString(aBuffer & 0xFF);
if (temp.length() == 1) {
temp = "0" + temp;
}
h = h + " " + temp;
}

return h;

}