连接示例¶
[1]:
import redis
连接到本地运行的默认 Redis 实例。¶
[2]:
connection = redis.Redis()
connection.ping()
[2]:
True
默认情况下,Redis 返回二进制响应,要解码它们,请使用 decode_responses=True¶
[3]:
decode_connection = redis.Redis(decode_responses=True)
connection.ping()
[3]:
True
连接到 Redis 实例,指定主机和端口以及凭据。¶
[4]:
user_connection = redis.Redis(host='localhost', port=6380, username='dvora', password='redis', decode_responses=True)
user_connection.ping()
[4]:
True
通过 SSL 连接到 Redis 实例。¶
[5]:
ssl_connection = redis.Redis(host='localhost', port=6666, ssl=True, ssl_cert_reqs="none")
ssl_connection.ping()
[5]:
True
通过 SSL 连接到 Redis 实例,同时指定自签名 SSL 证书。¶
[6]:
import os
ROOT = os.path.join(os.getcwd(), "..", "..")
CERT_DIR = os.path.abspath(os.path.join(ROOT, "docker", "stunnel", "keys"))
ssl_certfile=os.path.join(CERT_DIR, "server-cert.pem")
ssl_keyfile=os.path.join(CERT_DIR, "server-key.pem")
ssl_ca_certs=os.path.join(CERT_DIR, "server-cert.pem")
ssl_cert_conn = redis.Redis(
host="localhost",
port=6666,
ssl=True,
ssl_certfile=ssl_certfile,
ssl_keyfile=ssl_keyfile,
ssl_cert_reqs="required",
ssl_ca_certs=ssl_ca_certs,
)
ssl_cert_conn.ping()
[6]:
True
通过指定 URL 方案连接到 Redis 实例。¶
参数传递给以下方案,作为 URL 方案的参数。
支持三种 URL 方案
redis://
创建一个 TCP 套接字连接。 https://www.iana.org/assignments/uri-schemes/prov/redisrediss://
创建一个 SSL 封装的 TCP 套接字连接。 https://www.iana.org/assignments/uri-schemes/prov/redissunix://
: 创建一个 Unix 域套接字连接。
[7]:
url_connection = redis.from_url("rediss://127.0.0.1:6666?ssl_cert_reqs=none&decode_responses=True&health_check_interval=2")
url_connection.ping()
[7]:
True
连接到 Sentinel 实例¶
[ ]:
from redis.sentinel import Sentinel
sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
sentinel.discover_master("redis-py-test")