python 對redis 鍵值對的操作


我們可以將Redis中的Hashes類型看成具有String Key和String Value的鍵值對容器。類似python中的dict,javascript的jaon,java 的map,每一個Hash可以存儲4294967295個鍵值對。

 1 # encoding:utf-8
 2 import redis
 3 import time
 4 
 5 
 6 def main():
 7     """
 8     redis-cli -h 127.0.0.1 -a test321
 9     """
10     redis_host = "127.0.0.1"
11     redis_password = "test321"
12     redis_cli = redis.StrictRedis(host=redis_host, password=redis_password)
13     try:
14         key = "TEST_KEY_1484"
15         # string
16         print redis_cli.delete(key)
17         print redis_cli.hset(key, "test1", 1)  # 設置 key={test1:1}
18         print redis_cli.hget(key, "test1")  # 獲取key[test1]
19         print redis_cli.hexists(key, "test1")  # 是否存在key[test1]
20         print redis_cli.hset(key, "test2", 2)  # 設置 key={test2:2}
21         print redis_cli.hlen(key)  # 查看key下的鍵值對數量
22         print redis_cli.hdel(key, "test1", "test2")  # 批量刪除key下的鍵,返回實際刪除的鍵數量
23         print redis_cli.hlen(key)  # 查看key下的鍵值對數量
24         print redis_cli.hexists(key, "test1")  # 是否存在key[test1]
25         print redis_cli.hsetnx(key, "test1", 1)   # 設置 key={test1:1}
26         print redis_cli.hsetnx(key, "test1", 1.11)   # 如果key[test1]已存在設置失敗
27         print redis_cli.hget(key, "test1")  # 獲取key[test1]
28         print redis_cli.hincrby(key, "test1", 2)   # 設置 key[test1] 累加2
29         print redis_cli.hget(key, "test1")  # 獲取key[test1]
30         print redis_cli.hset(key, "test2", 2)  # 設置 key={test2:2}
31         print redis_cli.hgetall(key)  # 獲取key,得到dict對象
32         print redis_cli.hkeys(key)  # 獲取key下的所有鍵,得到list對象
33         print redis_cli.hvals(key)  # 獲取key下的所有值,得到list對象
34         print redis_cli.hmget(key, "test1", "test2")  # 批量獲取key下的指定鍵,得到list對象
35         print redis_cli.hmset(key, {"test3": 3, "test4": 4})  # 批量設置鍵值,無則添加,有則覆蓋,
36         print redis_cli.hgetall(key)
37     except Exception as e:
38         print e.message
39     finally:
40         print redis_cli.delete(key)
41     return None
42 
43 
44 if __name__ == "__main__":
45     main()

 github:https://github.com/luohuaizhi/test/blob/master/testRedisDict.py


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM