从redis key nodejs弹出值的原子操作
Atomic action to pop num of values from redis key nodejs
我有一个 nodejs 应用程序和 redis 服务器。
该应用程序正在使用 redis client.lpush 进行推送,而我实际需要的是一种从 redis 中弹出对象范围并以原子方式迭代它弹出的对象的方法。
有多个客户端 运行 针对集群,我希望他们读取更新的密钥。
从 redis 3.2 开始你可以检查
- POP 和 SRANDMEMBER [https://redis.io/commands/spop#count-argument-extension]
- 将 LRANGE 与管道一起使用 [https://redis.io/topics/pipelining](管道将 运行 作为一个原子事务)
最终解决方案:
通过在多操作中使用 lrange 和 ltrim,应该确保两者都以原子方式执行,并且中间没有中断。
在下面的示例中,有一个在给定键上使用 multi 的用法,而 count 表示要迭代的对象数。它 returns 第一个(最旧的)n 个对象(通过使用 lrange 和给定的计数)然后从 redis 中删除它们(根据给定的计数使用 trim)。
static multiExecutionRedis (key, count){
return new Promise((resolve, reject) => {
console.log("running multi execution in the client");
let client = Reporter.cache;
let multi = client.multi();
multi.lrange(key, (count * -1), -1)
.ltrim(key, 0, (++count) * -1)
.exec((error, data) => {
if (error) {
console.log(error);
reject(error);
} else {
console.log("returning valid data");
resolve(data[0]);
}
});
});
对于redis > 4.0,可以查看这里https://github.com/RedisLabsModules/redex#rxlists
您可以使用Redis事务。 Redis事务是将以顺序和原子方式发生的事务。您可以阅读交易 here
你可以在 redis 中使用 MULTI 命令来做到这一点。
如果您正在使用 redis(著名的 npm redis 客户端),那么它会公开 MULTI 函数。你可以阅读 multi here
您可以使用 multi -
var redis = require("redis"),
client = redis.createClient(), multi;
// start a separate multi command queue
multi = client.multi();
multi.lpop("keyName", function() {
// do your thing
multi.exec(function (err, replies) {
console.log(replies); // 101, 2
});
});
// drains multi queue and runs atomically
我有一个 nodejs 应用程序和 redis 服务器。 该应用程序正在使用 redis client.lpush 进行推送,而我实际需要的是一种从 redis 中弹出对象范围并以原子方式迭代它弹出的对象的方法。 有多个客户端 运行 针对集群,我希望他们读取更新的密钥。
从 redis 3.2 开始你可以检查
- POP 和 SRANDMEMBER [https://redis.io/commands/spop#count-argument-extension]
- 将 LRANGE 与管道一起使用 [https://redis.io/topics/pipelining](管道将 运行 作为一个原子事务)
最终解决方案:
通过在多操作中使用 lrange 和 ltrim,应该确保两者都以原子方式执行,并且中间没有中断。 在下面的示例中,有一个在给定键上使用 multi 的用法,而 count 表示要迭代的对象数。它 returns 第一个(最旧的)n 个对象(通过使用 lrange 和给定的计数)然后从 redis 中删除它们(根据给定的计数使用 trim)。
static multiExecutionRedis (key, count){
return new Promise((resolve, reject) => {
console.log("running multi execution in the client");
let client = Reporter.cache;
let multi = client.multi();
multi.lrange(key, (count * -1), -1)
.ltrim(key, 0, (++count) * -1)
.exec((error, data) => {
if (error) {
console.log(error);
reject(error);
} else {
console.log("returning valid data");
resolve(data[0]);
}
});
});
对于redis > 4.0,可以查看这里https://github.com/RedisLabsModules/redex#rxlists
您可以使用Redis事务。 Redis事务是将以顺序和原子方式发生的事务。您可以阅读交易 here
你可以在 redis 中使用 MULTI 命令来做到这一点。
如果您正在使用 redis(著名的 npm redis 客户端),那么它会公开 MULTI 函数。你可以阅读 multi here
您可以使用 multi -
var redis = require("redis"),
client = redis.createClient(), multi;
// start a separate multi command queue
multi = client.multi();
multi.lpop("keyName", function() {
// do your thing
multi.exec(function (err, replies) {
console.log(replies); // 101, 2
});
});
// drains multi queue and runs atomically