python操作redis

1. 准备工作

  1. 安装好 redisRedisPy库
  2. RedisDump 可以用来做数据导入或导出

    2. RedisPy库

    RedisPy库 提供两个类 redisStrictRedis 来实现 Redis 的命令操作。

StrictRedis 实现了绝大部分官方命令,参数也一一对应。

redisStrictRedis 的子类,主要功能是用于向后兼容旧版本库里的几个方法。

推荐使用 StrictRedis

连接 Redis

1
2
3
4
5
from redis import StrictRedis
# localhost port=6379 默认数据库 password=password
redis = StrictRedis(host='localhost', port=6379, db=0, password='password')
redis.set('name', 'weilai')
print(redis.get('name'))

使用ConnectionPool 连接

1
2
3
4
5
6
7
from redis import StrictRedis, ConnectionPool

pool = ConnectionPool(host='localhost', port=6379, db=0, password=password)
# localhost port=6379 默认数据库 password=password
redis = StrictRedis(connection_pool=pool)
#redis.set('name', 'weilai')
print(redis.get('name'))

ConnectionPool 还支持通过 url 来构建

1
2
3
redis://[:password]@host:port/db  # tcp
rediss://[:password]@host:port/db # tcp +ssl
unix://[:password]@/path/to/socket.sock?db=db # UNIX socket 连接

eg:

1
2
3
4
url = 'redis://:password@localhost:6379/0'
pool = ConnectionPool.from_url(url)
redis = StrictRedis(connection_pool=pool)
print(redis.get('name'))

类 改写

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
33
34
35
36
37
38
39
40
41
import redis

class TestString:
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379, db=0)

def test_set(self):
result = self.r.set('name2','weilai2')
print(result)
return result

def test_get(self):
result = self.r.get('name2')
print(result)
return result

def test_mset(self):
d = {
'name3' : 'user3',
'name4' : 'user4'
}
result = self.r.mset(d)
print(result)
return result

def test_mget(self):
l = ['name3', 'name4']
result = self.r.mget(l)
print(result)
return result


def main():
str_obj = TestString()
str_obj.test_set()
str_obj.test_get()
str_obj.test_mset()
str_obj.test_mget()

if __name__ == '__main__':
main()