python - DB - 连接redis

直接上示例代码:

import redis


# redis连接
r = redis.Redis(host='192.168.1.1', port=6379, password='mima', decode_responses=True)  # 连接redis,默认db0
r.set('zyname', 'zy')   # 向redis中写入键值对,key='zyname', value='zy'
print(r['zyname'])      # 打印key='zyname'的value值, 打印:zy
print(r.get('zyname'))  # 打印key='zyname'的value值,打印:zy
print(type(r.get('zyname')))  # 打印value的类型,打印:<class 'str'>


# 连接池
pool = redis.ConnectionPool(host='192.168.1.1', port=6379, password='mima', db=16, decode_responses=True)  # 连接db16
r1 = redis.Redis(connection_pool=pool)
r1.set('zyname1', 'zy111')
print(r.get('zyname1'))  # 打印:zy111


keys = r1.keys()
print(type(keys))  # 打印:<class 'list'>
print(keys)  # 打印库中所有的key

aa = r1.get('ABC:DEF:VSYY:742795435')  # 获取键的值(键中的冒号,代表文件夹层级结构)
print(aa)

 

posted @ 2021-07-06 10:52  小虫虫大虫虫  阅读(194)  评论(0)    收藏  举报