node.js 与 redis:同步还是异步? [英] node.js with redis: synchronous or asynchronous?

查看:48
本文介绍了node.js 与 redis:同步还是异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序(node/express/redis)中,我使用一些代码同时更新数据库中的几个项目:

In my app (node / express / redis), I use some code to update several items in DB at the same time:

app.put('myaction', function(req, res){
    // delete stuff
    db.del("key1");
    db.srem("set1", "test");

    // Add stuff
    db.sadd("set2", "test2");
    db.sadd("set3", "test3");
    db.hmset("hash1", "k11", "v11", "k21", "v21");
    db.hmset("hash2", "k12", "v12", "k22", "v22");
    // ...

    // Send response back
    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({ "status" : "ok" }));

    res.end(); 
});

我能确定所有这些操作都会在方法返回之前执行吗?我关心的是异步处理.因为我没有在 db 动作中使用回调函数,这样可以吗?

Can I be sure ALL those actions will be performed before the method returns ? My concern is the asynchronous processing. As I do not use callback function in the db actions, will this be alright ?

推荐答案

使用 MULTI/EXEC 命令创建命令队列并连续执行它们.然后使用回调发送一个连贯的响应(成功/失败).请注意,您必须使用 Redis 的 AOF 来避免 - 在崩溃的情况下 - 数据库状态与您的逻辑不一致,因为只有队列中的一部分命令被执行:即 MULTI/EXEC 在执行时不是事务性的.这是一个有用的参考.

Use the MULTI/EXEC command to create a queue of your commands and execute them in a row. Then use a callback to send a coherent response back (success/failure). Note that you must use Redis' AOF to avoid that - in case of crash - the db state is not coherent with your logic because only a part of the commands in the queue were executed: i.e. MULTI/EXEC is not transactional upon execution. This is a useful reference.

这篇关于node.js 与 redis:同步还是异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆