background image

Aug 20 2020

Redis Data Types 介紹

前言

這篇文章其實是以前在整理Redis的文件時所做的一些資料,再拿出來寫是因為現在同事剛好也需要這樣的資訊。

Redis在4.0之前其實只有5個資料型態,不過到了現在新的版本多了一些不同的形態如stream, geo等等,不過本篇只會針對原有的string, sort set, hash set, set, list這五個形態來做說明。

String 型別

String 型態可以存放 binary, string, integer, float資料,在官網的說明是最基礎的型態,單一個Key可以存放月512MB的資料。

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.

redis 官方網站

String 使用的幾個場景介紹

  1. 圖片快取 (使用binary)
  2. Configuration
  3. 累計次數、觀看累計次數

不過根據我的使用經驗來說,資料量在1Kb內擁有較好的網路傳輸,當今天你存放的string資料大於1kb,我建議轉換成binary資料,透過Gzip做壓縮 才存放到Redis中才會有較好的快取效果

HashSet

Hash set是用來存放一組相同性質的資料,這些資料HashSet(or Dictionary)或是物件的某一屬性,與String較為不同的是他可以取回單一個欄位資料 但String必須取回所有資料(若透過Redis module可以取得Json特定的資料),單一個Key可以存放2<sup>32</sup> - 1的資料欄位,

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (e.g. A User with a number of fields like name, surname, age, and so forth):

redis 官方網站

Hashes的使用場景

  1. 每次只需要取用一部分的資料
  2. C#的Dictionary或HashSet資料型態

List

List 資料型態可以想像成程式語言中的Array物件或是你可以把它時作成Queue或是Stack的物件。List 單一個Key可以存放2<sup>32</sup> - 1

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.

redis 官方網站

List的使用場景

  • List 物件
  • 無序資料
  • Queue 物件
  • Stack 物件
  • Array 物件

Set

類似於List的資料格式但不能存入相同的資料,所以內容是不能重複的預設也不會幫你排序,Sets 單一個Key可以存放2<sup>32</sup> - 1

Set的使用場景

  1. 文章中的Tag標籤
  2. 用來排除相同資料

Sorted Set

Sorted Set從名字就可以知道他是一個經過排序的Set所以當你每次有資料異動時都會自動的為你重新排序採用的是快速排序的演算法, 這個資料結構可以說是Redis操作的時候成本最高的一個結構吧!通常的時間成本是**O(log(N))**N為Key所存放的資料總量,另外他跟Set很相似內容是不能重複的

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.

redis 官方網站

Sorted Set的使用場景

其實也沒什麼好說的,需要有序的資料用他準沒錯

其他

其他資料還有Bitmaps, HyperLogLogs, geo, stream等等,目前我也沒有實際使用過,所以就不在此介紹了

參考連結

Redis Data Types

文章標籤