安装 redis 依赖包
npm install redis
var redis = require('redis'),
config = require('../config'),
dbConfig = config.redis,
RDS_PORT = dbConfig.port, //端口号
RDS_HOST = dbConfig.host, //服务器IP
RDS_PWD = dbConfig.pass, //密码
RDS_OPTS = {auth_pass: RDS_PWD},
client = redis.createClient(RDS_PORT, RDS_HOST, RDS_OPTS);
client.on('ready',function(res){
console.log('ready');
});
client.on('end',function(err){
console.log('end');
});
client.on('error', function (err) {
console.log(err);
});
client.on('connect',function(){
console.log('redis connect success!');
});
实测代码段
var redis = require("redis");
var client = redis.createClient(5555, "127.0.0.1");
client.AUTH("123456")
function getRedisData() {
//客户端连接redis成功后执行回调
client.on("ready", function () {
//订阅消息
client.subscribe("Channel1");
console.log("订阅成功。。。");
});
client.on("error", function (error) {
console.log("Redis Error " + error);
});
//监听订阅成功事件
client.on("subscribe", function (channel, count) {
console.log("client subscribed to " + channel + "," + count + "total subscriptions");
});
//收到消息后执行回调,message是redis发布的消息
client.on("message", function (channel, message) {
console.log(message);
//dealWithMsg(message);
});
//监听取消订阅事件
client.on("unsubscribe", function (channel, count) {
console.log("client unsubscribed from" + channel + ", " + count + " total subscriptions")
});
}
//function dealWithMsg(message) {
//按照message查询内容
//client1.zscore("z", message, function (err, reply) {
// console.log(message + "的内容是:" + reply);
//});
//}
//getRedisData();