Redis 中有删除单个 Key 的指令 del
,但好像没有批量删除 Key 的指令,不过我们可以借助 Linux
的 xargs 指令
来完成这个动作
1.使用命令行批量删除redis的key
语法
./redis-cli -h IP -p PORT -a PASSWORD -n NUM keys 'key*' | xargs ./redis-cli -h IP -p PORT -a PASSWORD -n NUM del
- IP:redis服务器的IP地址
- PORT:redis服务的端口
- PASSWORD :redis服务的密码
- NUM:redis库的下标
记得以上批量删除,需要退出redis的命令行模式下操作。必须要指定redis的路径
-
连上redis
./redis-cli -h ip -p 端口 -a 密码 -
选择数据库
select 数据库下标 -
模糊查询key是否存在
keys ‘UPLOAD_*’
-
执行
exit
命令 退出redis -
删除 端口为 6585 密码为 123456 且数据库为1 中所有UPLOAD_开头的key
/usr/bin/redis-cli -n 1 -p 6585 -a 123456 keys 'UPLOAD_*' | xargs /usr/bin/redis-cli -n 1 -p 6585 -a 123456 del
2.使用图形界面工具RedisDesktopManager
新版本的RedisDesktopManager目前支持通过分组批量删除key
-
打开软件,点击左下角的“Connect to Redis Server”新建redis链接
-
配置:
- 连接的别名(Name:自定义)
- Host(redis服务的ip)
- 端口(port)
- 密码(Auth)连接到redis服务
-
选择库,并模糊匹配key
4.在需要删除的key分组上右击“Delete Namaspace
”删除分组
3.使用jedis批量删除keys
- 引入jedis包
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.7.0</version></dependency>
- 使用jedisApi连接redis
//连接redis ,redis的默认端口是6379
Jedis jedis = new Jedis ("localhost",6379); //验证密码,如果没有设置密码这段代码省略
jedis.auth("password");
//连接
jedis.connect();//断开连接
jedis.disconnect();
- 编写批量删除的方法
方法将需要删除的key转换成数组传入jedis.del(keys)批量删除key
// java代码public static void deleteByPattern(Jedis jedis, String pattern) {Set<String> keys = jedis.keys(pattern);if(keys != null && !keys.isEmpty()) {String keyArr[] = new String[keys.size()];jedis.del(keys.toArray(keyArr));}}// jedis的del方法源码public Long del(final String... keys) {checkIsInMultiOrPipeline();client.del(keys);return client.getIntegerReply();}