Redis新手指南:在node中使用redis

Redis簡介

Redis是一個高性能的key-value數據庫,Redis把數據存在內存中,並在磁盤中記錄數據的變化。由於將數據存在內存中,因此數據操做很是快。node

安裝

以windows環境爲例,先下載windows版本的redis,地址以下:3.2.100
下載完成後,解壓,我這裏解壓到D:redis目錄下git

clipboard.png

開啓服務

打開一個 cmd 窗口,進入目錄到 D:redis,運行 redis-server.exe redis.windows.conf。github

clipboard.png

出現上面界面,則redis已經在本機端口6379啓動了服務,那麼接下來,即可以用客戶端鏈接到redis服務端了。redis

在node中使用redis

首先,安裝驅動:npm install redis數據庫

redis支持多種數據類型,經常使用的有鍵/值對,哈希表,鏈表,集合等。npm

普通數據

咱們先來看看如何存儲和獲取鍵/值對。windows

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();
})

運行,結果以下
clipboard.png數組

哈希表

哈希表有點相似ES6中的Map。運維

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();
});

運行,結果以下:函數

clipboard.png

鏈表

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();
});

運行,結果以下:

clipboard.png

集合

相似JS中的Set,集合中的元素必須是惟一的,其性能: 大O表示法中的O(1)

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();
});

運行,結果以下:

clipboard.png

信道

Redis超越了數據存儲的傳統職責,它還提供了信道,信道是數據傳遞機制,提供了發佈/預約功能。

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接受到信息後,在控制檯打印出了相關信息。
運行,結果以下:

clipboard.png

小結

本篇只是對Redis進行了最基本介紹,想要得到更多信息,能夠參考:
redis documentation
node_redis
Redis實戰
Redis開發與運維

相關文章
相關標籤/搜索