Posted on

npm module – ioredis介紹

Redis介紹

Redis是REmote DIctionary Server(遠程字典服務器)的縮寫,它以字典結構(key-value鍵值對結構)存儲數據,並允許其他應用通過TCP協議讀寫字典中的內容。所以,redis是一個key-value存儲系統,或者說是一個key-value數據庫。

Redis的內存存儲和持久化Redis數據庫中的所有數據都存儲在內存中。由於內存的讀寫速度遠快於硬盤,因此Redis在性能上對比其他基於硬盤存儲的數據庫有非常明顯的優勢,在一臺普通的筆記本電腦上,edis可以在一秒內讀寫超過十萬個鍵值。將數據存儲在內存中也有問題,例如,程序退出後內存中的數據會丟失。不過 Redis提供了對持久化的支持,即將可以內存中的數據異步寫入到硬盤中,同時不影響繼續提供服務

ioredis介紹


ioredis是一個功能強大的功能強大的Redis客戶,已被世界上最大的在線商務公司阿里巴巴和許多其他了不起的公司所使用。

  • 功能齊全。它支持Cluster,Sentinel,Pipelining,當然還支持Lua腳本和Pub / Sub(具有二進制消息的支持)。
  • 高性能。
  • 令人愉快的API。它與Node回調和本機Promise一起使用。
  • 命令參數和答复的轉換。
  • ansparent key prefixing
  • Lua腳本的抽象,允許您定義自定義命令。
  • 支持二進制數據。
  • 支持TLS。
  • Support for offline queue and ready checking
  • 支持 ES6 類型, 如: Map and Set
  • 支持GEO命令(Redis 3.2不穩定)。
  • 複雜的錯誤處理策略。
  • 支持NAT映射。

使用範例

下面是一個簡單的使用範例

"use strict";

const Redis = require("ioredis");
const MyService = require("path/to/my/service");

// Create a custom connector that fetches sentinels from an external call
class AsyncSentinelConnector extends Redis.SentinelConnector {
  constructor(options = {}) {
    // Placeholder
    options.sentinels = options.sentinels || [
      { host: "localhost", port: 6379 }
    ];

    // SentinelConnector saves options as its property
    super(options);
  }

  connect(eventEmitter) {
    return MyService.getSentinels().then(sentinels => {
      this.options.sentinels = sentinels;
      this.sentinelIterator = new Redis.SentinelIterator(sentinels);
      return Redis.SentinelConnector.prototype.connect.call(this, eventEmitter);
    });
  }
}

const redis = new Redis({
  Connector: AsyncSentinelConnector
});

// ioredis supports all Redis commands:
redis.set("foo", "bar");
redis.get("foo", function(err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});
redis.del("foo");

// Or using a promise if the last argument isn't a function
redis.get("foo").then(function(result) {
  console.log(result);
});

// Arguments to commands are flattened, so the following are the same:
redis.sadd("set", 1, 3, 5, 7);
redis.sadd("set", [1, 3, 5, 7]);

// All arguments are passed directly to the redis server:
redis.set("key", 100, "EX", 10);

// Change the server configuration
redis.config("set", "notify-keyspace-events", "KEA");

更多範例請見: https://github.com/luin/ioredis/tree/master/examples