[英]How correctly use Redis with Koa (node.js)
I try to get an information from a redis db and return it as the body of the response to the user. 我尝试从redis db获取信息并将其作为响应主体返回给用户。 First, here is a code that fails :
首先,这是一个失败的代码:
var redis = require("redis"),
koa = require("koa");
var app = koa(),
port = process.argv[2] || 3000,
client = redis.createClient();
app.use(function* (next) {
client.get("test", function (err, res) {
this.body = res;
});
yield next;
});
app.listen(port);
console.log("listen on port " + port)
Surely because the yield calls end before the callback is called. 当然,因为yield调用在调用回调之前结束。
Then here is a code that success : 然后这是一个成功的代码:
function askRedit (callback) {
client.get("test", callback);
}
app.use(function* (next) {
this.body = yield askRedit;
yield next;
});
But I clearly misunderstand why the second one is working. 但我显然误解了为什么第二个工作正常。 Does the
yield
in yield askRedit
have the same behavior than the one in yield next
? 请问
yield
的yield askRedit
具有比在同一个行为yield next
?
EDIT : I just seen a page that seems to answers a little : https://github.com/visionmedia/co/blob/master/examples/redis.js 编辑:我刚刚看到一个似乎有点回答的页面: https : //github.com/visionmedia/co/blob/master/examples/redis.js
So now I will try to understand these misterious yield.. is this a way of doing synchronous things with asynchronous calls ? 所以现在我将尝试理解这些神奇的产量..这是一种用异步调用做同步事情的方法吗?
Here is the correct solution : 这是正确的解决方案:
"Use strict";
var redis = require("redis"),
coRedis = require("co-redis"),
koa = require("koa");
var app = koa(),
port = process.argv[2] || 3000,
db = redis.createClient(),
dbCo = coRedis(db);
app.use(function* () {
yield dbCo.set("test", 42);
this.body = yield dbCo.get("test");
});
app.listen(port);
console.log("listen on port " + port)
theses links helped : 这些链接帮助:
https://github.com/koajs/workshop/tree/master/01-co https://github.com/koajs/workshop/tree/master/01-co
http://www.jongleberry.com/koa.html http://www.jongleberry.com/koa.html
and "co-redis" of course 当然还有“共同复兴”
Thanks to myself ! 谢谢你!
You could also use: 你也可以使用:
var koa = require('koa');
var app = koa();
var redis = require('then-redis');
var db = redis.createClient('tcp://redis:6379');
db.set('my-key', 0);
app.use(function *(){
db.incrby('my-key', 5);
this.body = yield db.get('my-key');
});
app.listen(9000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.