获取Redis所有的key
开放中
获取Redis所有的key
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import java.util.ArrayList;
import java.util.List;
public class RedisKeyInfo {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost", 6379);
// 获取所有的key
List<String> keys = getAllKeys(jedis);
// 获取每个key的信息
List<KeyInfo> keyInfos = getKeyInfos(jedis, keys);
// 打印每个key的信息
for (KeyInfo keyInfo : keyInfos) {
System.out.println(keyInfo);
}
jedis.close();
}
// 获取所有的key
private static List<String> getAllKeys(Jedis jedis) {
List<String> keys = new ArrayList<>();
String cursor = "0";
ScanParams scanParams = new ScanParams().count(100);
do {
ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
keys.addAll(scanResult.getResult());
cursor = scanResult.getStringCursor();
} while (!cursor.equals("0"));
return keys;
}
// 获取每个key的信息
private static List<KeyInfo> getKeyInfos(Jedis jedis, List<String> keys) {
List<KeyInfo> keyInfos = new ArrayList<>();
for (String key : keys) {
KeyInfo keyInfo = new KeyInfo();
keyInfo.setKey(key);
keyInfo.setType(jedis.type(key));
keyInfo.setTtl(jedis.ttl(key));
keyInfos.add(keyInfo);
}
return keyInfos;
}
// 封装key的信息
private static class KeyInfo {
private String key;
private String type;
private Long ttl;
// getter和setter方法
@Override
public String toString() {
return "KeyInfo{" +
"key='" + key + '\'' +
", type='" + type + '\'' +
", ttl=" + ttl +
'}';
}
}
}
请注册或登录再回复