连接到服务器

将您的 Python 应用连接到 Redis 数据库

基本连接

连接到 localhost 上的 6379 端口,在 Redis 中设置一个值,并检索它。在 Python 中,所有响应都以字节形式返回。要接收解码后的字符串,请设置 decode_responses=True。有关更多连接选项,请参阅 这些示例

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

存储和检索简单字符串。

r.set('foo', 'bar')
# True
r.get('foo')
# bar

存储和检索字典。

r.hset('user-session:123', mapping={
    'name': 'John',
    "surname": 'Smith',
    "company": 'Redis',
    "age": 29
})
# True

r.hgetall('user-session:123')
# {'surname': 'Smith', 'name': 'John', 'company': 'Redis', 'age': '29'}

连接到 Redis 集群

要连接到 Redis 集群,请使用 RedisCluster

from redis.cluster import RedisCluster

rc = RedisCluster(host='localhost', port=16379)

print(rc.get_nodes())
# [[host=127.0.0.1,port=16379,name=127.0.0.1:16379,server_type=primary,redis_connection=Redis<ConnectionPool<Connection<host=127.0.0.1,port=16379,db=0>>>], ...

rc.set('foo', 'bar')
# True

rc.get('foo')
# b'bar'

有关更多信息,请参阅 redis-py 集群

使用 TLS 连接到生产环境中的 Redis

部署应用时,请使用 TLS 并遵循 Redis 安全 指南。

import redis

r = redis.Redis(
    host="my-redis.cloud.redislabs.com", port=6379,
    username="default", # use your Redis user. More info https://redis.ac.cn/docs/latest/operate/oss_and_stack/management/security/acl/
    password="secret", # use your Redis password
    ssl=True,
    ssl_certfile="./redis_user.crt",
    ssl_keyfile="./redis_user_private.key",
    ssl_ca_certs="./redis_ca.pem",
)
r.set('foo', 'bar')
# True

r.get('foo')
# b'bar'

有关更多信息,请参阅 redis-py TLS 示例

使用客户端缓存连接

客户端缓存是一种减少客户端和服务器之间网络流量的技术,从而提高性能。有关客户端缓存的工作原理以及如何有效使用它的更多信息,请参阅 客户端缓存简介

要启用客户端缓存,连接到服务器时需添加额外参数

  • protocol:(必需)您必须在此处传递值 3,因为客户端缓存需要 RESP3 协议。
  • cache_config:(必需)在此处传递 cache_config=CacheConfig() 以启用客户端缓存。

以下示例展示了到默认主机和端口 localhost:6379 的最简单的客户端缓存连接。上面描述的所有连接变体都接受这些参数,因此您可以以完全相同的方式将客户端缓存用于连接池或集群连接。

注意

客户端缓存需要 redis-py v5.1.0 或更高版本。为了最大程度地兼容所有 Redis 产品,Redis v7.4 或更高版本支持客户端缓存。

Redis 服务器产品 支持 CSC 的选择加入/选择退出模式和广播模式,但这些模式目前尚未由 redis-py 实现。

import redis
from redis.cache import CacheConfig

r = redis.Redis(
    protocol=3,
    cache_config=CacheConfig(),
    decode_responses=True
)

r.set("city", "New York")
cityNameAttempt1 = r.get("city")    # Retrieved from Redis server and cached
cityNameAttempt2 = r.get("city")    # Retrieved from cache

如果您使用 redis-cli 连接到同一个 Redis 数据库并运行 MONITOR 命令,您可以看到缓存正在工作。如果您运行上面的代码,并注释掉 cache_config 行,您应该在 MONITOR 的输出中看到以下内容:

1723109720.268903 [...] "SET" "city" "New York"
1723109720.269681 [...] "GET" "city"
1723109720.270205 [...] "GET" "city"

服务器响应了两个 get("city") 调用。如果您再次运行代码,并取消注释 cache_config,您将看到:

1723110248.712663 [...] "SET" "city" "New York"
1723110248.713607 [...] "GET" "city"

第一个 get("city") 调用联系了服务器,但第二个调用由缓存满足。

从缓存中移除项

您可以使用 delete_by_redis_keys() 方法从缓存中移除单个键。这将移除与这些键相关联的所有缓存项,因此来自多键命令(如 MGET)和复合数据结构(如哈希)的所有结果将立即清除。以下示例显示了从缓存中移除单个键的效果:

r.hget("person:1", "name") # Read from the server
r.hget("person:1", "name") # Read from the cache

r.hget("person:2", "name") # Read from the server
r.hget("person:2", "name") # Read from the cache

cache = r.get_cache()
cache.delete_by_redis_keys(["person:1"])

r.hget("person:1", "name") # Read from the server
r.hget("person:1", "name") # Read from the cache

r.hget("person:2", "name") # Still read from the cache

您还可以使用 flush() 方法清除所有缓存项

r.hget("person:1", "name") # Read from the server
r.hget("person:1", "name") # Read from the cache

r.hget("person:2", "name") # Read from the cache
r.hget("person:2", "name") # Read from the cache

cache = r.get_cache()
cache.flush()

r.hget("person:1", "name") # Read from the server
r.hget("person:1", "name") # Read from the cache

r.hget("person:2", "name") # Read from the server
r.hget("person:2", "name") # Read from the cache

如果任何连接(包括来自连接池的连接)断开,客户端也会自动刷新缓存。

使用连接池连接

对于生产环境的使用,您应该使用连接池来管理连接,而不是单独打开和关闭连接。连接池维护多个打开的连接并高效地重用它们。当您从池中打开一个连接时,连接池会分配其中一个打开的连接。当您随后关闭同一连接时,它实际上并没有关闭,而是简单地返回到池中供重用。这避免了重复连接和断开连接的开销。有关更多信息,请参阅 连接池和多路复用

使用以下代码通过连接池进行连接

import redis

pool = redis.ConnectionPool().from_url("redis://localhost")
r1 = redis.Redis().from_pool(pool)
r2 = redis.Redis().from_pool(pool)
r3 = redis.Redis().from_pool(pool)

r1.set("wind:1", "Hurricane")
r2.set("wind:2", "Tornado")
r3.set("wind:3", "Mistral")

r1.close()
r2.close()
r3.close()

pool.close()
评价此页面
返回顶部 ↑