gpt4 book ai didi

node.js - ioredis 按模式删除所有键

转载 作者:IT王子 更新时间:2023-10-29 05:57:37 28 4
gpt4 key购买 nike

我将 ioredis 与 express (nodejs) 一起使用我知道有一种方法可以通过这样的模式删除键:

redis-cli KEYS "sample_pattern:*" | xargs redis-cli DEL

但是,有没有办法使用 ioredis 来做到这一点?

最佳答案

按模式删除键最直接的方法是使用keys命令获取与模式匹配的键,然后将它们一一删除,这类似于您提供的命令行示例。下面是一个使用 ioredis 实现的示例:

var Redis = require('ioredis');
var redis = new Redis();
redis.keys('sample_pattern:*').then(function (keys) {
// Use pipeline instead of sending
// one command each time to improve the
// performance.
var pipeline = redis.pipeline();
keys.forEach(function (key) {
pipeline.del(key);
});
return pipeline.exec();
});

然而,当您的数据库有大量键(比如一百万)时,keys 将阻塞数据库几秒钟。在这种情况下,scan 更有用。 ioredis 具有 scanStream 功能,可帮助您轻松地遍历数据库:

var Redis = require('ioredis');
var redis = new Redis();
// Create a readable stream (object mode)
var stream = redis.scanStream({
match: 'sample_pattern:*'
});
stream.on('data', function (keys) {
// `keys` is an array of strings representing key names
if (keys.length) {
var pipeline = redis.pipeline();
keys.forEach(function (key) {
pipeline.del(key);
});
pipeline.exec();
}
});
stream.on('end', function () {
console.log('done');
});

不要忘记查看scan 命令的官方文档以获取更多信息:http://redis.io/commands/scan .

关于node.js - ioredis 按模式删除所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968537/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com