• Read / write
  • Message Queue
  • Pub/Sub
  • Stream
  • Bitmap (chunk)
  • Redis cluster replication

Redis là gì?

Redis (Remote dictionary server) là 1 csdl NoSQL mã nguồn mở, hoạt động dựa trên cơ chế lưu trữ dữ liệu dưới dạng key-value trong bộ nhớ ram (in-memory) nên tốc độ truy vấn cực kì nhanh chóng. Ngoài việc sử dụng làm csdl, còn dùng làm cache, message queue, pub/sub. Hỗ trợ nhiều cấu trúc dữ liệu khác nhau: string, list, set, hash, sorted, sets, ….

Dữ liệu của redis được lưu dưới dạng document. 1 csdl NoSql và tất cả các key được đánh index. Nhờ vậy, việc truy xuất dữ liệu vô cùng nhanh chóng. Từ đó giúp chúng ta giải quyết được nhiều bài toán khác nhau như: Caching, Queuing, event processing, pub/sub.

String

Limit: 512 MB

Using ioredis or node-redis with nodejs

  • Structure: unstructured text / binary or simple counter, bit sets, or integer collections.
  • Operations: get, set, append, increment, decrement, bitwise operations.
  • Suitable for: Unstructured documents, counters, flags, bitmaps (setbit, getbit).
const { createClient } = require('redis');

const redis = createClient();

redis.connect()
.then(() => {
  typeString()
})

async function typeString() {
  const resSet = await redis.set('dat:1', 'nqdat.com');
  console.log(resSet); // OK
  const result = await redis.get('dat:1');
  console.log(result); // nqdat.com
}

You may ask SET to fail ì the key already exists, or the opposite, that it only succeed if the key already exists:

async function typeString() {
  const resSet = await redis.set('dat:1', 'nqdat.com', { NX: true });
  console.log(resSet); // OK: if key not exist | null: if key already exist (not update new value)
}
// opposite
async function typeString() {
  const resSet = await redis.set('dat:1', 'nqdat.com', { XX: true });
  console.log(resSet); // OK: if key already exist | null: if key not exist (not add key-value)
}

Using MSET and MGET are also useful for reduced latency.

async function typeString() {
  const res = await redis.mSet([
    ['dat:1', 'n'],
    ['dat:2', 'q'],
    ['dat:3', 'dat.com'],
  ])
  console.log(res); // OK

  const get = await redis.mGet(['dat:1', 'dat:2', 'dat:3']);
  console.log(get); // ['n', 'q', 'dat.com']
}

Strings as counters

Even if strings are basic values of Redis, there are interesting operations you can perform with them. For instance, one is atomic increment

async function atomic() {
  await redis.set('up', 0);
  const resUp = await redis.incr('up');
  console.log(resUp); // 1
  const resUpBy = await redis.incrBy('up', 3);
  console.log(resUpBy); // 4

  await redis.set('down', 0);
  const resDown = await redis.decr('down');
  console.log(resDown); // -1
  const resDownBy = await redis.decrBy('down', 3);
  console.log(resDownBy); // -4
}

Caution

increment, decrement no need init, default incrBy is 1 , decrBy is -1

Basic commands

Getting and setting Strings

  • SET: stores a string value.
  • SETNX: stores a string value only if the key doesn’t already exist. Useful for implementing locks.
  • GET: retrieves a string value.
  • MGET: retrieves multiple string values in a single operation.
  • MSET: stores many string values for many keys.

Managing counters

  • INCR: atomically increments counters stored at a given key by 1.
  • INCRBY: atomically increments counters stored at a given key.
  • DECR, DECRBY are opposite.
  • Another command exists for floating point counters: INCREBYFLOAT