Python操作Redis

安装并导入redis 

  pip install redis

  from  redis  import  Redis

Python操作Redis之普通连接

from redis import  Redis
# conn = Redis()
#连接对象
conn = Redis(host='localhost', port=6379,db=0)
result = conn.get('name')
print(result.decode('utf8'))

Python操作Redis之连接池

#redis连接池
import redis
#pool必须是单例的
POOL = redis.ConnectionPool(host="localhost",password="root",
                            port=6379,max_connections=100)  #创造连接池,最多能放多少链接

r = redis.Redis(connection_pool=POOL)  #取出一个链接
result = r.get('name')
print(result)

#使用模块导入的方式,使用单例
##get_redis_pool.py
import redis
POOL = redis.ConnectionPool(host="localhost",password="root",
port=6379,max_connections=100) #创造连接池,最多能放多少链接

#引用
from Redis import  get_redis_pool
r = redis.Redis(connection_pool=get_redis_pool.POOL) #取出一个链接
result = r.get('name')
print(result)

 字符串操作

set(name, value,ex=None, px=None, nx=False, xx=False, keepttl=False)

参数说明:

  ex:设置过期时间(秒)

  px:设置过期时间(毫秒)

  nx:如果设置为True,则只有name不存在时,当前set操作才会执行,如果存在就不做操作

  xx:如果设置为True,则只有name存在时,当前set操作才执行,值存在则修改,若不存在则不做设置新值操作

mset操作

conn.mset({'name1':'test1','name2':'test2'})   #一次连接,设置多个key-value

mget

result = conn.mget(['name1','name2'])  #为空时返回None
print(result)

Hash操作

#hset
# conn.hset('message','name','wushaoyu')
# conn.hset('message','name2','shaoyuwu')

# ret = conn.hget('message','name')  #只能取一个
# print(ret)

#hmset
# conn.hmset('msg',{'key1':'value1','key2':'value2'})

#hmget
# ret = conn.hmget('message','name','name2')
# print(ret)
# ret = conn.hmget('message',['name','name2'])
# print(ret)

#hgetall
ret = conn.hgetall('msg')   #尽量少用
print(ret)

#hlen 获取msg对应的hash的键值对个数
ret = conn.hlen('msg')
print(ret)

#hkeys 获取msg对应hash的key的值
conn.hkeys('msg')

#hvals 获取msg对应hash的value的值
conn.hvals('msg')

#hexists  检测msg对应的hash中是否含有key1
conn.hexists('msg','key1')

#hdel   删除msg对应的hash中是的键
conn.hdel('msg','key1')

 列表操作

 

posted @ 2021-07-25 15:08  wushaoyu  阅读(3814)  评论(0编辑  收藏  举报