nodejs--redis模块

1、简介

2、使用

(1)连接

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!');
});

(2)字符串

client.set('color', 'red', redis.print);
client.get('color', function(err, value) {
  if (err) throw err;
  console.log('Got: ' + value)
  client.quit();
})

在这里插入图片描述

(3)哈希表

client.hmset('kitty', {
  'age': '2-year-old',
  'sex': 'male'
}, redis.print);
client.hget('kitty', 'age', function(err, value) {
  if (err) throw err;
  console.log('kitty is ' + value);
});

client.hkeys('kitty', function(err, keys) {
  if (err) throw err;
  keys.forEach(function(key, i) {
    console.log(key, i);
  });
  client.quit();
});

在这里插入图片描述

(4)链表

client.lpush('tasks', 'Paint the house red.', redis.print);
client.lpush('tasks', 'Paint the house green.', redis.print);
client.lrange('tasks', 0, -1, function(err, items) {
  if (err) throw err;
  items.forEach(function(item, i) {
    console.log(' ' + item);
  });
  client.quit();
});

在这里插入图片描述

(5)集合

client.sadd('ip', '192.168.3.7', redis.print);
client.sadd('ip', '192.168.3.7', redis.print);
client.sadd('ip', '192.168.3.9', redis.print);
client.smembers('ip', function(err, members) {
  if (err) throw err;
  console.log(members);
  client.quit();
});

在这里插入图片描述

(6)信道(发布/订阅)

var redis = require('redis')
var clientA = redis.createClient(6379, '127.0.0.1')
var clientB = redis.createClient(6379, '127.0.0.1')

clientA.on('message', function(channel, message) {
  console.log('Client A got message from channel %s: %s', channel, message);
});
clientA.on('subscribe', function(channel, count) {
  clientB.publish('main_chat_room', 'Hello world!');
});
clientA.subscribe('main_chat_room');

上面代码中,clientA订阅了main_chat_room,这时clientA捕获到订阅事件,执行回调函数,clientB向main_chat_room发送了一条信息Hello world!
clientA接受到信息后,在控制台打印出了相关信息。
运行,结果如下:
在这里插入图片描述
学习链接:https://www.npmjs.com/package/redis
https://segmentfault.com/a/1190000015882650
https://www.cnblogs.com/zhaowinter/p/10776868.html
https://www.cnblogs.com/shaozhu520/p/10859276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值