Redis Overview

Redis 是什麼 ?

Redis (Remote Dictionary Server) 是一個 open-source 的 in-memory 的資料儲存系統,分類上屬於 NoSQL。資料儲存在記憶體中所以速度可以很快,根據需求也可以支援寫入硬碟。不過最常用的功能是作為 cache。

建立一個 cloud Redis database

  • 此網站去建立 free account
  • 選一個 cloud provider 後就會自動幫你建立 Redis database 了

基本操作 (Python)

  • 下載 Python 套件

    ​​​​pip install redis
    
  • 連線到 cloud Redis server

    • 先到剛剛的連結點到你的 database 中的 Public Endpoint > Connect > 選擇 Python 後複製 code 連結

    • Python 連線 (password 這邊可以到 database 的 Security 欄位中使用預設的)

      Image Not Showing Possible Reasons
      • The image was uploaded to a note which you don't have access to
      • The note which the image was originally uploaded to has been deleted
      Learn More →

      ​​​​​​​​import redis
      ​​​​​​​​r = redis.Redis(host='***', port=***, password='*******', decode_responses=True)
      

      這邊加 decode_responses 可以讓之後查找時回傳已經 decode 的值

  • Python API

    • CRUD
      Create: set, Read: get, Update: set, Delete: delete

      ​​​​​​​​# create, read, and update
      ​​​​​​​​>>> r.set('name', 'bob')
      ​​​​​​​​True
      ​​​​​​​​>>> r.get('name')
      ​​​​​​​​'bob'
      ​​​​​​​​>>> r.set('name', 'alice')
      ​​​​​​​​True
      ​​​​​​​​>>> r.get('name')
      ​​​​​​​​'alice'
      ​​​​​​​​>>> r.keys()
      ​​​​​​​​['name']
      ​​​​​​​​
      ​​​​​​​​# delete
      ​​​​​​​​>>> r.delete('name')
      ​​​​​​​​1 # 回傳刪除幾個 key
      ​​​​​​​​>>> r.keys()
      ​​​​​​​​[]
      
    • hset, hget, hdel,
      針對 hash 值的 key/value 做操作,以下例子可以把 hash1 當作一個 table

      ​​​​​​​​>>> r.hset("hash1", "key1", "value1")
      ​​​​​​​​1 
      ​​​​​​​​>>> r.hset("hash1", "key2", "value2")
      ​​​​​​​​1
      ​​​​​​​​>>> r.hkeys("hash1")
      ​​​​​​​​['key1', 'key2']
      ​​​​​​​​>>> r.hdel("hash1", "key1")
      ​​​​​​​​1
      ​​​​​​​​>>> r.hkeys("hash1")
      ​​​​​​​​['key2']