Background

這篇文章主要是看了一篇文章之後想要做一些重點整理而記錄的文章。推薦大家有興趣可以去看一下原文,原文中有介紹了在使用Redis要注意的某些地方。

1. Keep Track of Your Keys

  • Redis' schema-less nature makes it extremely difficult to make sense of your dataset's contents unless you use a solid nomenclature for your keys.

  • Using a proper naming methodology for your keys can make housekeeping of your database much easier.

  • When you namespace your keys by application or service – the convention is to use the colon (':') character to delimit parts of the key’s name

簡單的來說就是 Key - Value Database 的特性,導致你很難直接透過 Key 值來判斷裡面的資料放了什麼東西 & 它的功用。(因為沒有Table層來幫助你理解Data存放的規則)

因此在Redis中key的命名規則變得更加的重要。然後跟一般程式的命名規則不太一樣地方的是Redis適用:來間隔單字。

目前我自己的定義key的命名規則如下:

APPLICATIONNAME:ENV:ENTRYPOINT:UID(KEY):TIMESTAMP

  • APPLICATIONNAME: 應用程式名稱
  • ENV: 目前在哪個開發環境 (通常我會把qa&stg共用同一個redis,如果都拆開的話那這個部分就可以拿掉)
  • ENTRYPOINT: 這邊通常是指那個FUNTION呼叫的,方便Tracking
  • UID(KEY): 邏輯上的 unique key
  • TIMESTAMP: 方便作時間上的 Tracking

2. Keep Track of the Length of Your Key Names

  • For example: consider that storing 1,000,000 keys, each set with a 32 character value, will consume about 96MB when using 6-character key names, and 111MB with 12-character names (on 32-bit Redis server).

直接舉這個例子應該蠻有感的,這點主要是提醒我們Key的值不要設得太長,畢竟記憶體的儲存空間還是很昂貴的,但這點跟第一點是有點衝突的。(只能說魚與熊掌不能兼得lol)

3. Use the Right Data Structures

  • Instead of storing your data in thousands (or millions) of independent string values, consider grouping related data with the hash data structure.
  • In hash, we trust simplicity more than features, so nested data structures are not allowed, as expires of single fields are not allowed
  • Sorted sets are the most expensive data structure, both in terms of memory consumption and basic operations complexity
  • An often overlooked feature in Redis are bitmaps.
  • To count unique users that logged in today, we set up a bitmap where each user is identified by an offset value.
  • To calculate weekly or monthly metrics, we can simply compute the union of all the daily Bitmaps over the week or the month

Screen-Shot-2019-06-26-at-1.35.10-AM


  • 標題是個廢話?(lol)
  • 盡量把 string -> string map 的型態打包成 Hash (這可能需要想一個Rule來表示,這樣做可以省下大量的記憶體)
  • Sorted sets 也不意外啦,這麼powerful代價當然是高的
  • 我們常忽略掉 bitmaps,正確使用其實可以優化很多操作空間&時間。

4. Use SCAN, Never Use KEYS

  • SCAN enables you to retrieve keys in the keyspace using a cursor.
  • KEYS returns all matching elements at once, may block your Redis server and even exhaust its RAM resources
  • SCAN is accompanied by SSCAN, HSCAN and ZSCAN, which allow you to iterate the contents of sets, hashes and sorted sets (respectively).

就利用SCAN系列來取值,不要使用KEYS指令。

5. Use Server-Side Lua Scripts

  • When applied correctly, Lua scripts can make a world of difference in terms of performance and resource consumption.

簡單的說就是利用 Lua Scripts 可以增加 Redis 的效能,所以可以多加利用。

Reference