Node.js下使用Redis,首先:
1、有一台安装了Redis的服务器,当然,安装在本机也行
2、本机,也就是客户端,要装node.js
3、项目要安装nodejs_redis模块
注意第 3 点,不是在本机安装就行了,而是说,要在项目中安装(引用)。
方法是,DOS窗口,在项目目录下,输入
npm install redis
这样就将nodejs_redis下载一份,放到当前目录下了。看看,多了一个文件夹:node_modules\redis
编写以下代码,保存到当前目录下\hello.js
- var redis = require("redis"),
-
-
-
-
-
- client = redis.createClient(6379,'192.168.159.128',{});
-
-
-
-
-
-
-
- client.on("error", function (err) {
- console.log("Error " + err);
- });
-
- client.set("string key", "string val", redis.print);
-
-
-
- client.hset("hash key", "hashtest 1", "some value", redis.print);
- client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
-
- client.hkeys("hash key", function (err, replies) {
- console.log(replies.length + " replies:");
- replies.forEach(function (reply, i) {
- console.log(" " + i + ": " + reply);
- });
- client.hget("hash key","hashtest 1",redis.print);
-
-
-
-
-
-
- client.quit();
- });
运行:
DOS窗口,当前项目目录下,输入
node hello.js
参考资料:
https://github.com/mranney/node_redis