安装库
连接
r = redis.StrictRedis(host='localhost',port=6379,db=0)
操作
字符串相关操作
import redis
class TestString(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379)
print(self.r)
# 设置值
def test_set(self):
res = self.r.set('user1', 'juran-1')
print(res)
# 取值
def test_get(self):
res = self.r.get('user1')
print(res)
# 设置多个值
def test_mset(self):
d = {'user2': 'juran-2', 'user3': 'juran-3'}
res = self.r.mset(d)
# 取多个值
def test_mget(self):
l = ['user2', 'user3']
res = self.r.mget(l)
print(res)
# 删除
def test_del(self):
self.r.delete('user2')
列表相关操作
import redis
class TestList(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379)
# 插入记录
def test_push(self):
res = self.r.lpush('common', '1')
res = self.r.rpush('common', '2')
# res = self.r.rpush('jr', '123')
# 弹出记录
def test_pop(self):
res = self.r.lpop('common')
res = self.r.rpop('common')
# 范围取值
def test_range(self):
res = self.r.lrange('common', 0, -1)
print(res)
集合相关操作
import redis
class TestList(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379)
# 添加数据
def test_sadd(self):
res = self.r.sadd('set01', '1', '2')
lis = ['Cat', 'Dog']
res = self.r.sadd('set02', lis)
# 删除数据
def test_del(self):
res = self.r.srem('set01', 1)
# 随机删除数据
def test_pop(self):
res = self.r.spop('set02')
哈希相关操作
import redis
class TestList(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379)
# 批量设值
def test_hset(self):
dic = {'id': 1, 'name': 'huawei'}
res = self.r.hmset('mobile', dic)
# 批量取值
def test_hgetall(self):
res = self.r.hgetall('mobile')
# 判断是否存在 存在返回1 不存在返回0
def test_hexists(self):
res = self.r.hexists('mobile', 'id')
print(res)