Redis Data Types

Redis 支援多種的資料型態(Data Types),字串型態最大支援到 512MB,但在使用上還是要特別小心,單一鍵值不宜存放過大的鍵值,或是單一陣列(list)不宜有過多的成員,因為當單一鍵值過大,或是成員過多會容易產生 hotkey 或是 bigkey 的問題,也容易造成 Redis Engine 遭遇效能上的瓶頸。

Jerry’s Notes
What’s next?
3 min readMar 18, 2022

--

!! 請注意,Redis 是單執行序服務,當大量存取大鍵值(Bigkey/Hotkey)時,容易造成延遲增加,進而造成前端應用程序 timeout 或異常,所以如何選擇資料型態(Data Types)、以及如何去存取數據,是很重要的。

  • Strings: Strings are the most basic kind of Redis value. Redis Strings are binary safe, this means that a Redis string can contain any kind of data, for instance a JPEG image or a serialized Ruby object. A String value can be at max 512 Megabytes in length. — String類型可以是字符串(簡單的字符串、複雜的字符串(例如JSON、XML))、數字(整數、浮點數),甚至是二進制(圖片、音頻、視頻),但是值最大不能超過512MB
  • Lists: Redis Lists are simply lists of strings, sorted by insertion order. It is possible to add elements to a Redis List pushing new elements on the head (on the left) or on the tail (on the right) of the list. — Lists 字符串列表,按照插入順序排序。你可以添加一個元素到列表的頭部(左邊)或者尾部(右邊)一個列表最多可以包含 2³² — 1 個元素。
  • Sets: Redis Sets are an unordered collection of Strings. It is possible to add, remove, and test for existence of members in O(1) (constant time regardless of the number of elements contained inside the Set). — Set 是 string 類型的無序字串集合.
  • ZSet — 有序集合 — string類型元素的集合,且不允許重複的成員。
  • Hashes: Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects. — Hashes 哈希鍵值對的集合。 Redis的哈希值是字符串字段和字符串值之間的映射。但當大量使用Hashes時,容易造成hotkey issue,因為當鍵值被 hashes 過後,鍵值會被存放在特定 slot 中,會造成該slot/shard特別忙碌、內存使用量、負載不平均的問題。(這部份在hotkey/bigkey問題及建議來說明)。
  • Sorted sets: Redis Sorted Sets are, similarly to Redis Sets, non-repeating collections of Strings. The difference is that every member of a Sorted Set is associated with score, that is used in order to take the sorted set ordered, from the smallest to the greatest score. While members are unique, scores may be repeated. — 用來排序資料使用!! 存入資料時,會關連一個數字。
  • Bitmaps and HyperLogLogs: Redis also supports Bitmaps and HyperLogLogs which are actually data types based on the String base type, but having their own semantics.
  • streams: append-only collections of map-like entries that provide an abstract log data

Q: How does a Set and a Sorted Set data type differ?

Sorted sets are a data type which is similar to a mix between a Set and a Hash. Like sets, sorted sets are composed of unique, non-repeating string elements, so in some sense a sorted set is a set as well.

Sorted sets are implemented via a dual-ported data structure containing both a skip list and a hash table, so every time we add an element Redis performs an O(log(N)) operation. That’s good, but when we ask for sorted elements Redis does not have to do any work at all, it’s already all sorted.

Strings — 字符串操作範例

Hashes — 哈希值操作範例

Lists — 列表操作範例

Set 是 string 類型的無序集合操作範例

--

--

Jerry’s Notes
What’s next?

An cloud support engineer focus on troubleshooting with customer reported issue ,and cloud solution architecture.