连接到服务器

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

基本连接

连接到本地主机的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 Clustering

使用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.io/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 或更高版本支持。
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()
RATE THIS PAGE
Back to top ↑