import redis
class TestString(object):
# 初始化 连接redis数据库
def __init__(self):
self.r = redis.StrictRedis(host='127.0.0.1', port=6379)
# 设置值
def test_set(self):
res = self.r.set('user1', 'yueyue-1')
print(res)
# 取值
def test_get(self):
res = self.r.get('user1')
print(res,type(res))
res = res.decode('UTF-8')
print(res, type(res))
# 设置多个值
def test_mset(self):
d = {
'user2': 'yueyue-2',
'user3': 'yueyue-3'
}
res = self.r.mset(d)
print(res)
# 取多个值
def test_mget(self):
l = ['user2', 'user3']
res = self.r.mget(l)
print(res)
# 删除
def test_del(self):
self.r.delete('user2')
if __name__ == '__main__':
t = TestString()
# t.test_set()
t.test_get()
import redis
class TestList(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379, db=1)
# 插入记录
def test_push(self):
res = self.r.lpush('common', '1')
print(res)
res = self.r.rpush('common', '2')
print(res)
# 弹出记录
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)
if __name__ == '__main__':
t = TestList()
# t.test_set()
# t.test_push()
t.test_range()
列表相关操作
集合相关操作
Plain Text复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import redis
class TestSet(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379, db=1)
# 添加数据
def test_sadd(self):
res = self.r.sadd('set01', '1', '2')
# redis升级到3.0以后不支持 bytes, string, int , float以外的数据类型。
# 删除数据
def test_del(self):
res = self.r.srem('set01', 1)
# 随机删除数据
def test_pop(self):
res = self.r.spop('set01')
if __name__ == '__main__':
t = TestSet()
# t.test_set()
# t.test_push()
t.test_pop()
哈希相关操作
Plain Text复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import redis
class TestHash(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379, db=1)
# 批量设值
def test_hset(self):
dic = {
'id': 1,
'name': 'huawei'
}
res = self.r.hmset('mobile', dic)
# 批量取值
def test_hgetall(self):
res = self.r.hgetall('mobile')
print(res)
# 判断是否存在 存在返回1 不存在返回0
def test_hexists(self):
res = self.r.hexists('mobile', 'id')
print(res)
if __name__ == '__main__':
t = TestHash()
# t.test_set()
# t.test_push()
t.test_hexists()