redis是目前使用最廣泛的緩存數據庫,沒有之一,並且不接受反駁(手動滑稽)
redis官方版支持大五種結構:key-value、list、set、zset、hash
這一集,我們主要討論hash,以python爲例。
在redis裏面,我們可以這麼存數據:
hset:{name: xiaoluo}
是吧,但是在絕大多數情況,比如後臺的restful接口,可能會是這樣的:
{"data":
"info":
{"name": "小羅",
"age" : 26,
"scores": [95, 97, 60, 89]
}
}
在官方的redis你得這麼來:
(1)先轉成str(str())
(2)set key value
用的時候得這麼來
(1)get key
(2)eval或者json.loads
行吧,這樣我也能接受了。但是,我想修改一部分,怎麼辦。比如我想把age改成25,在python裏得這麼辦:
(1)get key
(2)eval
(3)修改鍵值對
(4)轉成str
(5)set key
煩不煩煩不煩,複雜不復雜,繁瑣不繁瑣。還多了不少IO交互!
那redisjson就派上用場了。
https://redislabs.com,這個網站開發了很多redis的插件,如下:
其他的模塊大家自己去了解了解,其實最有用的還是redisjson,這次對redisjson做一些技術分享。
一、安裝(以ubuntu爲例)
(1)安裝好redis,這步就不細說了。
(2)安裝系統環境:apt-get install build-essential
(3)安裝redisjson插件:git clone https://github.com/RedisJSON/RedisJSON.git
(4)make編譯,假設redisjson的路徑爲:/opt/redisjson
(5)加載redisjson插件:redis-server --loadmodule /opt/redisjson/src/rejson.so
無報錯即安裝成功
二、python簡單示例
# coding=utf8
from rejson import Client
redis_con = Client(host='localhost', password='xxxxxx', decode_responses=True)
redis_con.flushdb()
data = {'name': '小羅',
'age': 25,
'goods': ['耳機', 'mbp', '😺'],
'detail': {'address': '北京', 'job': '碼畜'}}
# 插入數據
redis_con.jsonset('info', '.', data)
# 打印所有鍵,查看類型
print(redis_con.keys(), redis_con.jsontype('info'))
# goods append
redis_con.jsonarrappend('info', '.goods', '測試append')
# goods insert
redis_con.jsonarrinsert('info', '.goods', '1', '測試insert')
# 亂碼
print(redis_con.jsonget('info', '.'))
# 正常編碼
print(redis_con.jsonget('info', '.', no_escape=True))
# detail update
redis_con.jsonset('info', '.detail.salary', 'secret')
# detail modify
redis_con.jsonset('info', '.detail.job', '碼農')
print(redis_con.jsonget('info', '.', no_escape=True))
以上包括了python字典的絕大多數用法,這些也足夠平時開發用了。注意no_escape,如果字段包括非常規英文、符號和數字,需要置爲True。
更多說明文檔,請移步:https://redislabs.com