Node.js 和 redis 看起来很热,但我被烧毁了。我无法优雅地克服看似非常简单的任务:
给定 3 个数字,检查前两个是否大于 10。如果是,则打印第三个数字。
我确实用这个相当滑稽的脚本完成了这项任务:
var http = require("http");
var redis = require("redis");
client = redis.createClient();
http.createServer(function(request, response) {
client.SET("key1", "11");
client.SET("key2", "9");
client.SET("key3", "3");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello\n\n");
client.GET("key1", function(err, reply) {
response.write(reply + "\n\n");
if(parseInt(reply) > 10) {
client.GET("key2", function(err, reply) {
response.write(reply + "\n\n");
if(parseInt(reply) > 10) {
client.GET("key3", function(err, reply) {
response.write(reply + "\n\n");
response.end();
client.end();
});
} else {
response.end();
client.end();
}
});
} else {
response.end();
client.end();
}
});
}).listen(8000);
我注意到的几件事是:
- 每次我想要一个新的 GET 时都需要嵌套吗?
response.end()
需要在某个地方调用write
s 才能出现。如何避免在else
块中重复它们?
然后我尝试了这种查询数据库的方式:
http.createServer(function(request, response) {
client.SET("key1", "11");
client.SET("key2", "9");
client.SET("key3", "3");
var key1 = 0;
var key2 = 0;
var key3 = 0;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello\n\n");
client.GET("key1", function(err, reply) {
response.write(reply + "\n\n");
key1 = parseInt(reply);
});
client.GET("key2", function(err, reply) {
response.write(reply + "\n\n");
key2 = parseInt(reply);
});
client.GET("key3", function(err, reply) {
response.write(reply + "\n\n");
key3 = parseInt(reply);
});
response.write(key1 + "\n\n");
response.write(key2 + "\n\n");
response.write(key3 + "\n\n");
response.end();
client.end();
经过一番阅读和思考,我的解释是代码response.write
在异步 GET 返回之前到达 s,然后关闭响应,因此内部写入永远不会发生。至少我从第一个示例中注意到,可以轻松调用 SET,但我不知道(这似乎并不重要)它们是否实际上是按该顺序设置的。
所以,也许我正在做一些不适合node和redis的事情。而且我一定遗漏了一些基本而明显的东西。我需要做什么才能升级?
或者告诉我我必须回到 PhpMyAdmin :(