一、安装

使用pip命令安装Redis模块

pip install redis

二、连接方式

1、简单连接

简单连接只需要导入redis,然后将参数传入StrictRedis即可,代码如下:

# redis_test文件
import redis
REDIS_INFO = {
    "host": "127.0.0.1",
    "password": "123456",
    "port": 6379,
    "db": 0,
    "max_connections": 100
}
connect = redis.StrictRedis(host=REDIS_INFO['host'], port=REDIS_INFO['port'], password=REDIS_INFO['password'], db=REDIS_INFO['db'])
connect.set("key", "velue")

2、连接池连接

使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池

# config.py文件
from redis import ConnectionPool
REDIS_INFO = {
    "host": "127.0.0.1",
    "password": "123456",
    "port": 6379,
    "db": 0,
    "max_connections": 100
}
POOL = ConnectionPool(host=REDIS_INFO['host'], port=REDIS_INFO['port'], password=REDIS_INFO['password'],
                      db=REDIS_INFO['db'], max_connections=REDIS_INFO['max_connections'])

# redis_test文件
import redis
from config import POOL

connet = redis.Redis(connection_pool=POOL)
connet.set("key", "velue")

添加微信