yuan wen : segmentfault.com/a/119000001…node
首先,安裝驅動:npm install redisredis
redis支持多種數據類型,經常使用的有鍵/值對,哈希表,鏈表,集合等。npm
普通數據
咱們先來看看如何存儲和獲取鍵/值對。segmentfault
咱們先來看看如何存儲和獲取鍵/值對。數組
var redis = require('redis')
var client = redis.createClient(6379, '127.0.0.1')
client.on('error', function (err) {
console.log('Error ' + err);
});
// 1 鍵值對
client.set('color', 'red', redis.print);
client.get('color', function(err, value) {
if (err) throw err;
console.log('Got: ' + value)
client.quit();
})
複製代碼
哈希表有點相似ES6中的Map。bash
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();
});
複製代碼
Redis鏈表相似JS數組,lpush向鏈表中添加值,lrange獲取參數start和end範圍內的鏈表元素, 參數end爲-1,代表到鏈表中最後一個元素。 注意:隨着鏈表長度的增加,數據獲取也會逐漸變慢(大O表示法中的O(n))性能
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();
});
複製代碼
相似JS中的Set,集合中的元素必須是惟一的,其性能: 大O表示法中的O(1)ui
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();
});
複製代碼
Redis超越了數據存儲的傳統職責,它還提供了信道,信道是數據傳遞機制,提供了發佈/預約功能。spa
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');
複製代碼