连接到 Redis (Connecting to Redis)

通用客户端(Generic Client)

这是用于直接连接到标准 Redis 节点的客户端。

class redis.Redis(host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_keepalive_options=None, connection_pool=None, unix_socket_path=None, encoding='utf-8', encoding_errors='strict', charset=None, errors=None, decode_responses=False, retry_on_timeout=False, retry_on_error=None, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_ca_path=None, ssl_ca_data=None, ssl_check_hostname=False, ssl_password=None, ssl_validate_ocsp=False, ssl_validate_ocsp_stapled=False, ssl_ocsp_context=None, ssl_ocsp_expected_cert=None, ssl_min_version=None, ssl_ciphers=None, max_connections=None, single_connection_client=False, health_check_interval=0, client_name=None, lib_name='redis-py', lib_version='5.1.1', username=None, retry=None, redis_connect_func=None, credential_provider=None, protocol=2, cache=None, cache_config=None)[源代码]

Implementation of the Redis protocol.

This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.

Pipelines derive from this, implementing how the commands are sent and received to the Redis server. Based on configuration, an instance will either use a ConnectionPool, or Connection object to talk to redis.

It is not safe to pass PubSub or Pipeline objects between threads.

参数:
  • credential_provider (CredentialProvider | None)

  • protocol (int | None)

  • cache (CacheInterface | None)

  • cache_config (CacheConfig | None)

classmethod from_pool(connection_pool)[源代码]

Return a Redis client from the given connection pool. The Redis client will take ownership of the connection pool and close it when the Redis client is closed.

参数:

connection_pool (ConnectionPool)

返回类型:

Redis

classmethod from_url(url, **kwargs)[源代码]

Return a Redis client object configured from the given URL

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0

  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0

  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool's class initializer. In the case of conflicting arguments, querystring arguments always win.

参数:

url (str)

返回类型:

Redis

get_connection_kwargs()[源代码]

Get the connection's key-word arguments

返回类型:

Dict

get_encoder()[源代码]

Get the connection pool's encoder

返回类型:

Encoder

load_external_module(funcname, func)[源代码]

This function can be used to add externally defined redis modules, and their namespaces to the redis client.

funcname - A string containing the name of the function to create func - The function, being added to this class.

ex: Assume that one has a custom redis module named foomod that creates command named 'foo.dothing' and 'foo.anotherthing' in redis. To load function functions into this namespace:

from redis import Redis from foomodule import F r = Redis() r.load_external_module("foo", F) r.foo().dothing('your', 'arguments')

For a concrete example see the reimport of the redisjson module in tests/test_connection.py::test_loading_external_modules

返回类型:

None

lock(name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, lock_class=None, thread_local=True)[源代码]

Return a new Lock object using key name that mimics the behavior of threading.Lock.

If specified, timeout indicates a maximum life for the lock. By default, it will remain locked until release() is called.

sleep indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

blocking indicates whether calling acquire should block until the lock has been acquired or to fail immediately, causing acquire to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a blocking argument to acquire.

blocking_timeout indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or integer, both representing the number of seconds to wait.

lock_class forces the specified lock implementation. Note that as of redis-py 3.0, the only lock class we implement is Lock (which is a Lua-based lock). So, it's unlikely you'll need this parameter, unless you have created your own custom lock class.

thread_local indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:

time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.

thread-1 sets the token to "abc"

time: 1, thread-2 blocks trying to acquire my-lock using the

Lock instance.

time: 5, thread-1 has not yet completed. redis expires the lock

key.

time: 5, thread-2 acquired my-lock now that it's available.

thread-2 sets the token to "xyz"

time: 6, thread-1 finishes its work and calls release(). if the

token is not stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock.

In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage.

参数:
  • name (str)

  • timeout (float | None)

  • sleep (float)

  • blocking (bool)

  • blocking_timeout (float | None)

  • lock_class (None | Any)

  • thread_local (bool)

parse_response(connection, command_name, **options)[源代码]

Parses a response from the Redis server

pipeline(transaction=True, shard_hint=None)[源代码]

Return a new pipeline object that can queue multiple commands for later execution. transaction indicates whether all commands should be executed atomically. Apart from making a group of operations atomic, pipelines are useful for reducing the back-and-forth overhead between the client and server.

返回类型:

Pipeline

pubsub(**kwargs)[源代码]

Return a Publish/Subscribe object. With this object, you can subscribe to channels and listen for messages that get published to them.

set_response_callback(command, callback)[源代码]

Set a custom Response Callback

参数:
  • command (str)

  • callback (Callable)

返回类型:

None

transaction(func, *watches, **kwargs)[源代码]

Convenience method for executing the callable func as a transaction while watching all keys specified in watches. The 'func' callable should expect a single argument which is a Pipeline object.

参数:

func (Callable[[Pipeline], None])

返回类型:

None

哨兵客户端(Sentinel Client)

Redis Sentinel 提供 Redis 的高可用性。有些命令只能在以哨兵模式运行的 Redis 节点上执行。连接到这些节点并对它们执行命令需要使用哨兵连接。

连接示例(假设 Redis 在下面列出的端口上存在):

>>> from redis import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> sentinel.discover_master('mymaster')
('127.0.0.1', 6379)
>>> sentinel.discover_slaves('mymaster')
[('127.0.0.1', 6380)]

哨兵(Sentinel)

class redis.sentinel.Sentinel(sentinels, min_other_sentinels=0, sentinel_kwargs=None, force_master_ip=None, **connection_kwargs)[源代码]

Redis Sentinel cluster client

>>> from redis.sentinel import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
>>> master.set('foo', 'bar')
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
>>> slave.get('foo')
b'bar'

sentinels is a list of sentinel nodes. Each node is represented by a pair (hostname, port).

min_other_sentinels defined a minimum number of peers for a sentinel. When querying a sentinel, if it doesn't meet this threshold, responses from that sentinel won't be considered valid.

sentinel_kwargs is a dictionary of connection arguments used when connecting to sentinel instances. Any argument that can be passed to a normal Redis connection can be specified here. If sentinel_kwargs is not specified, any socket_timeout and socket_keepalive options specified in connection_kwargs will be used.

connection_kwargs are keyword arguments that will be used when establishing a connection to a Redis server.

discover_master(service_name)[源代码]

Asks sentinel servers for the Redis master's address corresponding to the service labeled service_name.

Returns a pair (address, port) or raises MasterNotFoundError if no master is found.

discover_slaves(service_name)[源代码]

Returns a list of alive slaves for service service_name

execute_command(*args, **kwargs)[源代码]

Execute Sentinel command in sentinel nodes. once - If set to True, then execute the resulting command on a single node at random, rather than across the entire sentinel cluster.

filter_slaves(slaves)[源代码]

Remove slaves that are in an ODOWN or SDOWN state

master_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[源代码]

Returns a redis client instance for the service_name master.

A SentinelConnectionPool class is used to retrieve the master's address before establishing a new connection.

NOTE: If the master's address has changed, any cached connections to the old master are closed.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

slave_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[源代码]

Returns redis client instance for the service_name slave(s).

A SentinelConnectionPool class is used to retrieve the slave's address before establishing a new connection.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

哨兵连接池(SentinelConnectionPool)

class redis.sentinel.SentinelConnectionPool(service_name, sentinel_manager, **kwargs)[源代码]

Sentinel backed connection pool.

If check_connection flag is set to True, SentinelManagedConnection sends a PING command right after establishing the connection.

rotate_slaves()[源代码]

Round-robin slave balancer

集群客户端(Cluster Client)

此客户端用于连接到 Redis 集群。

RedisCluster

class redis.cluster.RedisCluster(host=None, port=6379, startup_nodes=None, cluster_error_retry_attempts=3, retry=None, require_full_coverage=False, reinitialize_steps=5, read_from_replicas=False, dynamic_startup_nodes=True, url=None, address_remap=None, cache=None, cache_config=None, **kwargs)[源代码]
参数:
  • host (str | None)

  • port (int)

  • startup_nodes (List[ClusterNode] | None)

  • cluster_error_retry_attempts (int)

  • retry (Retry | None)

  • require_full_coverage (bool)

  • reinitialize_steps (int)

  • read_from_replicas (bool)

  • dynamic_startup_nodes (bool)

  • url (str | None)

  • address_remap (Callable[[Tuple[str, int]], Tuple[str, int]] | None)

  • cache (CacheInterface | None)

  • cache_config (CacheConfig | None)

determine_slot(*args)[源代码]

Figure out what slot to use based on args.

Raises a RedisClusterException if there's a missing key and we can't

determine what slots to map the command to; or, if the keys don't all map to the same key slot.

classmethod from_url(url, **kwargs)[源代码]

Return a Redis client object configured from the given URL

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0

  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0

  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool's class initializer. In the case of conflicting arguments, querystring arguments always win.

get_connection_kwargs()[源代码]

Get the connections' key-word arguments

get_default_node()[源代码]

Get the cluster's default node

get_encoder()[源代码]

Get the connections' encoder

get_node_from_key(key, replica=False)[源代码]

Get the node that holds the key's slot. If replica set to True but the slot doesn't have any replicas, None is returned.

keyslot(key)[源代码]

Calculate keyslot for a given key. See Keys distribution model in https://redis.io/topics/cluster-spec

load_external_module(funcname, func)[源代码]

This function can be used to add externally defined redis modules, and their namespaces to the redis client.

funcname - A string containing the name of the function to create func - The function, being added to this class.

lock(name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, lock_class=None, thread_local=True)[源代码]

Return a new Lock object using key name that mimics the behavior of threading.Lock.

If specified, timeout indicates a maximum life for the lock. By default, it will remain locked until release() is called.

sleep indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

blocking indicates whether calling acquire should block until the lock has been acquired or to fail immediately, causing acquire to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a blocking argument to acquire.

blocking_timeout indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or integer, both representing the number of seconds to wait.

lock_class forces the specified lock implementation. Note that as of redis-py 3.0, the only lock class we implement is Lock (which is a Lua-based lock). So, it's unlikely you'll need this parameter, unless you have created your own custom lock class.

thread_local indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:

time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.

thread-1 sets the token to "abc"

time: 1, thread-2 blocks trying to acquire my-lock using the

Lock instance.

time: 5, thread-1 has not yet completed. redis expires the lock

key.

time: 5, thread-2 acquired my-lock now that it's available.

thread-2 sets the token to "xyz"

time: 6, thread-1 finishes its work and calls release(). if the

token is not stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock.

In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage.

monitor(target_node=None)[源代码]

Returns a Monitor object for the specified target node. The default cluster node will be selected if no target node was specified. Monitor is useful for handling the MONITOR command to the redis server. next_command() method returns one command from monitor listen() method yields commands from monitor.

on_connect(connection)[源代码]
Initialize the connection, authenticate and select a database and send

READONLY if it is set during object initialization.

pipeline(transaction=None, shard_hint=None)[源代码]
Cluster impl:

Pipelines do not work in cluster mode the same way they do in normal mode. Create a clone of this object so that simulating pipelines will work correctly. Each command will be called directly when used and when calling execute() will only return the result stack.

pubsub(node=None, host=None, port=None, **kwargs)[源代码]

Allows passing a ClusterNode, or host&port, to get a pubsub instance connected to the specified node

set_default_node(node)[源代码]

Set the default node of the cluster. :param node: 'ClusterNode' :return True if the default node was set, else False

set_response_callback(command, callback)[源代码]

Set a custom Response Callback

ClusterNode

class redis.cluster.ClusterNode(host, port, server_type=None, redis_connection=None)[源代码]

异步客户端(Async Client)

完整示例见: 这里

此客户端用于异步与 Redis 通信。

class redis.asyncio.client.Redis(*, host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_keepalive_options=None, connection_pool=None, unix_socket_path=None, encoding='utf-8', encoding_errors='strict', decode_responses=False, retry_on_timeout=False, retry_on_error=None, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_ca_data=None, ssl_check_hostname=False, ssl_min_version=None, ssl_ciphers=None, max_connections=None, single_connection_client=False, health_check_interval=0, client_name=None, lib_name='redis-py', lib_version='5.1.1', username=None, retry=None, auto_close_connection_pool=None, redis_connect_func=None, credential_provider=None, protocol=2)[源代码]

Implementation of the Redis protocol.

This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.

Pipelines derive from this, implementing how the commands are sent and received to the Redis server. Based on configuration, an instance will either use a ConnectionPool, or Connection object to talk to redis.

参数:
  • host (str)

  • port (int)

  • db (str | int)

  • password (str | None)

  • socket_timeout (float | None)

  • socket_connect_timeout (float | None)

  • socket_keepalive (bool | None)

  • socket_keepalive_options (Mapping[int, int | bytes] | None)

  • connection_pool (ConnectionPool | None)

  • unix_socket_path (str | None)

  • encoding (str)

  • encoding_errors (str)

  • decode_responses (bool)

  • retry_on_timeout (bool)

  • retry_on_error (list | None)

  • ssl (bool)

  • ssl_keyfile (str | None)

  • ssl_certfile (str | None)

  • ssl_cert_reqs (str)

  • ssl_ca_certs (str | None)

  • ssl_ca_data (str | None)

  • ssl_check_hostname (bool)

  • ssl_min_version (TLSVersion | None)

  • ssl_ciphers (str | None)

  • max_connections (int | None)

  • single_connection_client (bool)

  • health_check_interval (int)

  • client_name (str | None)

  • lib_name (str | None)

  • lib_version (str | None)

  • username (str | None)

  • retry (Retry | None)

  • auto_close_connection_pool (bool | None)

  • credential_provider (CredentialProvider | None)

  • protocol (int | None)

async aclose(close_connection_pool=None)[源代码]

Closes Redis client connection

参数:

close_connection_pool (bool | None) -- decides whether to close the connection pool used by this Redis client, overriding Redis.auto_close_connection_pool. By default, let Redis.auto_close_connection_pool decide whether to close the connection pool.

返回类型:

None

close(close_connection_pool=None)[源代码]

Alias for aclose(), for backwards compatibility

参数:

close_connection_pool (bool | None)

返回类型:

None

async execute_command(*args, **options)[源代码]

Execute a command and return a parsed response

classmethod from_pool(connection_pool)[源代码]

Return a Redis client from the given connection pool. The Redis client will take ownership of the connection pool and close it when the Redis client is closed.

参数:

connection_pool (ConnectionPool)

返回类型:

Redis

classmethod from_url(url, single_connection_client=False, auto_close_connection_pool=None, **kwargs)[源代码]

Return a Redis client object configured from the given URL

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0

  2. If using the redis:// or rediss:// schemes, the path argument

    of the url, e.g. redis://localhost/0

  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool's class initializer. In the case of conflicting arguments, querystring arguments always win.

参数:
  • url (str)

  • single_connection_client (bool)

  • auto_close_connection_pool (bool | None)

get_connection_kwargs()[源代码]

Get the connection's key-word arguments

get_encoder()[源代码]

Get the connection pool's encoder

load_external_module(funcname, func)[源代码]

This function can be used to add externally defined redis modules, and their namespaces to the redis client.

funcname - A string containing the name of the function to create func - The function, being added to this class.

ex: Assume that one has a custom redis module named foomod that creates command named 'foo.dothing' and 'foo.anotherthing' in redis. To load function functions into this namespace:

from redis import Redis from foomodule import F r = Redis() r.load_external_module("foo", F) r.foo().dothing('your', 'arguments')

For a concrete example see the reimport of the redisjson module in tests/test_connection.py::test_loading_external_modules

lock(name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, lock_class=None, thread_local=True)[源代码]

Return a new Lock object using key name that mimics the behavior of threading.Lock.

If specified, timeout indicates a maximum life for the lock. By default, it will remain locked until release() is called.

sleep indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

blocking indicates whether calling acquire should block until the lock has been acquired or to fail immediately, causing acquire to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a blocking argument to acquire.

blocking_timeout indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or integer, both representing the number of seconds to wait.

lock_class forces the specified lock implementation. Note that as of redis-py 3.0, the only lock class we implement is Lock (which is a Lua-based lock). So, it's unlikely you'll need this parameter, unless you have created your own custom lock class.

thread_local indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:

time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.

thread-1 sets the token to "abc"

time: 1, thread-2 blocks trying to acquire my-lock using the

Lock instance.

time: 5, thread-1 has not yet completed. redis expires the lock

key.

time: 5, thread-2 acquired my-lock now that it's available.

thread-2 sets the token to "xyz"

time: 6, thread-1 finishes its work and calls release(). if the

token is not stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock.

In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage.

参数:
  • name (bytes | str | memoryview)

  • timeout (float | None)

  • sleep (float)

  • blocking (bool)

  • blocking_timeout (float | None)

  • lock_class (Type[Lock] | None)

  • thread_local (bool)

返回类型:

Lock

async parse_response(connection, command_name, **options)[源代码]

Parses a response from the Redis server

参数:
  • connection (Connection)

  • command_name (str | bytes)

pipeline(transaction=True, shard_hint=None)[源代码]

Return a new pipeline object that can queue multiple commands for later execution. transaction indicates whether all commands should be executed atomically. Apart from making a group of operations atomic, pipelines are useful for reducing the back-and-forth overhead between the client and server.

参数:
  • transaction (bool)

  • shard_hint (str | None)

返回类型:

Pipeline

pubsub(**kwargs)[源代码]

Return a Publish/Subscribe object. With this object, you can subscribe to channels and listen for messages that get published to them.

返回类型:

PubSub

set_response_callback(command, callback)[源代码]

Set a custom Response Callback

参数:
  • command (str)

  • callback (ResponseCallbackProtocol | AsyncResponseCallbackProtocol)

async transaction(func, *watches, shard_hint=None, value_from_callable=False, watch_delay=None)[源代码]

Convenience method for executing the callable func as a transaction while watching all keys specified in watches. The 'func' callable should expect a single argument which is a Pipeline object.

参数:
  • func (Callable[[Pipeline], Any | Awaitable[Any]])

  • watches (bytes | str | memoryview)

  • shard_hint (str | None)

  • value_from_callable (bool)

  • watch_delay (float | None)

异步集群客户端

RedisCluster (异步)

class redis.asyncio.cluster.RedisCluster(host=None, port=6379, startup_nodes=None, require_full_coverage=True, read_from_replicas=False, reinitialize_steps=5, cluster_error_retry_attempts=3, connection_error_retry_attempts=3, max_connections=2147483648, db=0, path=None, credential_provider=None, username=None, password=None, client_name=None, lib_name='redis-py', lib_version='5.1.1', encoding='utf-8', encoding_errors='strict', decode_responses=False, health_check_interval=0, socket_connect_timeout=None, socket_keepalive=False, socket_keepalive_options=None, socket_timeout=None, retry=None, retry_on_error=None, ssl=False, ssl_ca_certs=None, ssl_ca_data=None, ssl_cert_reqs='required', ssl_certfile=None, ssl_check_hostname=False, ssl_keyfile=None, ssl_min_version=None, ssl_ciphers=None, protocol=2, address_remap=None)[源代码]

Create a new RedisCluster client.

Pass one of parameters:

  • host & port

  • startup_nodes

Use await initialize() to find cluster nodes & create connections.
Use await close() to disconnect connections & close client.

Many commands support the target_nodes kwarg. It can be one of the NODE_FLAGS:

  • PRIMARIES

  • REPLICAS

  • ALL_NODES

  • RANDOM

  • DEFAULT_NODE

Note: This client is not thread/process/fork safe.

参数:
  • host (str | None) --

    Can be used to point to a startup node

  • port (str | int) --

    Port used if host is provided

  • startup_nodes (List[ClusterNode] | None) --

    ClusterNode to used as a startup node

  • require_full_coverage (bool) --

    When set to False: the client will not require a full coverage of the slots. However, if not all slots are covered, and at least one node has cluster-require-full-coverage set to yes, the server will throw a ClusterDownError for some key-based commands.
    When set to True: all slots must be covered to construct the cluster client. If not all slots are covered, RedisClusterException will be thrown.

  • read_from_replicas (bool) --

    Enable read from replicas in READONLY mode. You can read possibly stale data. When set to true, read commands will be assigned between the primary and its replications in a Round-Robin manner.

  • reinitialize_steps (int) --

    Specifies the number of MOVED errors that need to occur before reinitializing the whole cluster topology. If a MOVED error occurs and the cluster does not need to be reinitialized on this current error handling, only the MOVED slot will be patched with the redirected node. To reinitialize the cluster on every MOVED error, set reinitialize_steps to 1. To avoid reinitializing the cluster on moved errors, set reinitialize_steps to 0.

  • cluster_error_retry_attempts (int) --

    Number of times to retry before raising an error when TimeoutError or ConnectionError or ClusterDownError are encountered

  • connection_error_retry_attempts (int) --

    Number of times to retry before reinitializing when TimeoutError or ConnectionError are encountered. The default backoff strategy will be set if Retry object is not passed (see default_backoff in backoff.py). To change it, pass a custom Retry object using the "retry" keyword.

  • max_connections (int) --

    Maximum number of connections per node. If there are no free connections & the maximum number of connections are already created, a MaxConnectionsError is raised. This error may be retried as defined by connection_error_retry_attempts

  • address_remap (Callable[[Tuple[str, int]], Tuple[str, int]] | None) --

    An optional callable which, when provided with an internal network address of a node, e.g. a (host, port) tuple, will return the address where the node is reachable. This can be used to map the addresses at which the nodes _think_ they are, to addresses at which a client may reach them, such as when they sit behind a proxy.

  • db (str | int)

  • path (str | None)

  • credential_provider (CredentialProvider | None)

  • username (str | None)

  • password (str | None)

  • client_name (str | None)

  • lib_name (str | None)

  • lib_version (str | None)

  • encoding (str)

  • encoding_errors (str)

  • decode_responses (bool)

  • health_check_interval (float)

  • socket_connect_timeout (float | None)

  • socket_keepalive (bool)

  • socket_keepalive_options (Mapping[int, int | bytes] | None)

  • socket_timeout (float | None)

  • retry (Retry | None)

  • retry_on_error (List[Type[Exception]] | None)

  • ssl (bool)

  • ssl_ca_certs (str | None)

  • ssl_ca_data (str | None)

  • ssl_cert_reqs (str)

  • ssl_certfile (str | None)

  • ssl_check_hostname (bool)

  • ssl_keyfile (str | None)

  • ssl_min_version (TLSVersion | None)

  • ssl_ciphers (str | None)

  • protocol (int | None)

Rest of the arguments will be passed to the Connection instances when created
抛出:

RedisClusterException --

if any arguments are invalid or unknown. Eg:

  • db != 0 or None

  • path argument for unix socket connection

  • none of the host/port & startup_nodes were provided

参数:
  • host (str | None)

  • port (str | int)

  • startup_nodes (List[ClusterNode] | None)

  • require_full_coverage (bool)

  • read_from_replicas (bool)

  • reinitialize_steps (int)

  • cluster_error_retry_attempts (int)

  • connection_error_retry_attempts (int)

  • max_connections (int)

  • db (str | int)

  • path (str | None)

  • credential_provider (CredentialProvider | None)

  • username (str | None)

  • password (str | None)

  • client_name (str | None)

  • lib_name (str | None)

  • lib_version (str | None)

  • encoding (str)

  • encoding_errors (str)

  • decode_responses (bool)

  • health_check_interval (float)

  • socket_connect_timeout (float | None)

  • socket_keepalive (bool)

  • socket_keepalive_options (Mapping[int, int | bytes] | None)

  • socket_timeout (float | None)

  • retry (Retry | None)

  • retry_on_error (List[Type[Exception]] | None)

  • ssl (bool)

  • ssl_ca_certs (str | None)

  • ssl_ca_data (str | None)

  • ssl_cert_reqs (str)

  • ssl_certfile (str | None)

  • ssl_check_hostname (bool)

  • ssl_keyfile (str | None)

  • ssl_min_version (TLSVersion | None)

  • ssl_ciphers (str | None)

  • protocol (int | None)

  • address_remap (Callable[[Tuple[str, int]], Tuple[str, int]] | None)

classmethod from_url(url, **kwargs)[源代码]

Return a Redis client object configured from the given URL.

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to Connection when created. In the case of conflicting arguments, querystring arguments are used.

参数:
  • url (str)

  • kwargs (Any)

返回类型:

RedisCluster

async initialize()[源代码]

Get all nodes from startup nodes & creates connections if not initialized.

返回类型:

RedisCluster

async aclose()[源代码]

Close all connections & client if initialized.

返回类型:

None

close()[源代码]

alias for aclose() for backwards compatibility

返回类型:

None

get_nodes()[源代码]

Get all nodes of the cluster.

返回类型:

List[ClusterNode]

get_primaries()[源代码]

Get the primary nodes of the cluster.

返回类型:

List[ClusterNode]

get_replicas()[源代码]

Get the replica nodes of the cluster.

返回类型:

List[ClusterNode]

get_random_node()[源代码]

Get a random node of the cluster.

返回类型:

ClusterNode

get_default_node()[源代码]

Get the default node of the client.

返回类型:

ClusterNode

set_default_node(node)[源代码]

Set the default node of the client.

抛出:

DataError -- if None is passed or node does not exist in cluster.

参数:

node (ClusterNode)

返回类型:

None

get_node(host=None, port=None, node_name=None)[源代码]

Get node by (host, port) or node_name.

参数:
  • host (str | None)

  • port (int | None)

  • node_name (str | None)

返回类型:

ClusterNode | None

get_node_from_key(key, replica=False)[源代码]

Get the cluster node corresponding to the provided key.

参数:
  • key (str)

  • replica (bool) --

    Indicates if a replica should be returned
    None will returned if no replica holds this key

抛出:

SlotNotCoveredError -- if the key is not covered by any slot.

返回类型:

ClusterNode | None

keyslot(key)[源代码]

Find the keyslot for a given key.

See: https://redis.io/docs/manual/scaling/#redis-cluster-data-sharding

参数:

key (bytes | memoryview | str | int | float)

返回类型:

int

get_encoder()[源代码]

Get the encoder object of the client.

返回类型:

Encoder

get_connection_kwargs()[源代码]

Get the kwargs passed to Connection.

返回类型:

Dict[str, Any | None]

set_response_callback(command, callback)[源代码]

Set a custom response callback.

参数:
  • command (str)

  • callback (ResponseCallbackProtocol | AsyncResponseCallbackProtocol)

返回类型:

None

async execute_command(*args, **kwargs)[源代码]

Execute a raw command on the appropriate cluster node or target_nodes.

It will retry the command as specified by cluster_error_retry_attempts & then raise an exception.

参数:
  • args (bytes | memoryview | str | int | float) --

    Raw command args

  • kwargs (Any) --

抛出:

RedisClusterException -- if target_nodes is not provided & the command can't be mapped to a slot

返回类型:

Any

pipeline(transaction=None, shard_hint=None)[源代码]

Create & return a new ClusterPipeline object.

Cluster implementation of pipeline does not support transaction or shard_hint.

抛出:

RedisClusterException -- if transaction or shard_hint are truthy values

参数:
  • transaction (None | Any)

  • shard_hint (None | Any)

返回类型:

ClusterPipeline

lock(name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, lock_class=None, thread_local=True)[源代码]

Return a new Lock object using key name that mimics the behavior of threading.Lock.

If specified, timeout indicates a maximum life for the lock. By default, it will remain locked until release() is called.

sleep indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

blocking indicates whether calling acquire should block until the lock has been acquired or to fail immediately, causing acquire to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a blocking argument to acquire.

blocking_timeout indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or integer, both representing the number of seconds to wait.

lock_class forces the specified lock implementation. Note that as of redis-py 3.0, the only lock class we implement is Lock (which is a Lua-based lock). So, it's unlikely you'll need this parameter, unless you have created your own custom lock class.

thread_local indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:

time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.

thread-1 sets the token to "abc"

time: 1, thread-2 blocks trying to acquire my-lock using the

Lock instance.

time: 5, thread-1 has not yet completed. redis expires the lock

key.

time: 5, thread-2 acquired my-lock now that it's available.

thread-2 sets the token to "xyz"

time: 6, thread-1 finishes its work and calls release(). if the

token is not stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock.

In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage.

参数:
  • name (bytes | str | memoryview)

  • timeout (float | None)

  • sleep (float)

  • blocking (bool)

  • blocking_timeout (float | None)

  • lock_class (Type[Lock] | None)

  • thread_local (bool)

返回类型:

Lock

ClusterNode (异步)

class redis.asyncio.cluster.ClusterNode(host, port, server_type=None, *, max_connections=2147483648, connection_class=<class 'redis.asyncio.connection.Connection'>, **connection_kwargs)[源代码]

Create a new ClusterNode.

Each ClusterNode manages multiple Connection objects for the (host, port).

参数:
  • host (str)

  • port (str | int)

  • server_type (str | None)

  • max_connections (int)

  • connection_class (Type[Connection])

  • connection_kwargs (Any)

ClusterPipeline (异步)

class redis.asyncio.cluster.ClusterPipeline(client)[源代码]

Create a new ClusterPipeline object.

Usage:

result = await (
    rc.pipeline()
    .set("A", 1)
    .get("A")
    .hset("K", "F", "V")
    .hgetall("K")
    .mset_nonatomic({"A": 2, "B": 3})
    .get("A")
    .get("B")
    .delete("A", "B", "K")
    .execute()
)
# result = [True, "1", 1, {"F": "V"}, True, True, "2", "3", 1, 1, 1]

Note: For commands DELETE, EXISTS, TOUCH, UNLINK, mset_nonatomic, which are split across multiple nodes, you'll get multiple results for them in the array.

Retryable errors:
Redirection errors:
参数:

client (RedisCluster) --

Existing RedisCluster client

execute_command(*args, **kwargs)[源代码]

Append a raw command to the pipeline.

参数:
  • args (bytes | str | memoryview | int | float) --

    Raw command args

  • kwargs (Any) --

返回类型:

ClusterPipeline

async execute(raise_on_error=True, allow_redirections=True)[源代码]

Execute the pipeline.

It will retry the commands as specified by cluster_error_retry_attempts & then raise an exception.

参数:
  • raise_on_error (bool) --

    Raise the first error if there are any errors

  • allow_redirections (bool) --

    Whether to retry each failed command individually in case of redirection errors

抛出:

RedisClusterException -- if target_nodes is not provided & the command can't be mapped to a slot

返回类型:

List[Any]

连接(Connection)

完整示例见: 这里

连接(Connection)

class redis.connection.Connection(host='localhost', port=6379, socket_keepalive=False, socket_keepalive_options=None, socket_type=0, **kwargs)[源代码]

Manages TCP communication to and from a Redis server

连接 (异步)(Connection (Async))

class redis.asyncio.connection.Connection(*, host='localhost', port=6379, socket_keepalive=False, socket_keepalive_options=None, socket_type=0, **kwargs)[源代码]

Manages TCP communication to and from a Redis server

参数:
  • host (str)

  • port (str | int)

  • socket_keepalive (bool)

  • socket_keepalive_options (Mapping[int, int | bytes] | None)

  • socket_type (int)

连接池(Connection Pools)

完整示例见: 这里

ConnectionPool

class redis.connection.ConnectionPool(connection_class=<class 'redis.connection.Connection'>, max_connections=None, cache_factory=None, **connection_kwargs)[源代码]

Create a connection pool. If max_connections is set, then this object raises ConnectionError when the pool's limit is reached.

By default, TCP connections are created unless connection_class is specified. Use class:.UnixDomainSocketConnection for unix sockets.

Any additional keyword arguments are passed to the constructor of connection_class.

参数:
  • max_connections (int | None)

  • cache_factory (CacheFactoryInterface | None)

close()[源代码]

Close the pool, disconnecting all connections

返回类型:

None

disconnect(inuse_connections=True)[源代码]

Disconnects connections in the pool

If inuse_connections is True, disconnect connections that are current in use, potentially by other threads. Otherwise only disconnect connections that are idle in the pool.

参数:

inuse_connections (bool)

返回类型:

None

classmethod from_url(url, **kwargs)[源代码]

Return a connection pool configured from the given URL.

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0

  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0

  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool's class initializer. In the case of conflicting arguments, querystring arguments always win.

get_connection(command_name, *keys, **options)[源代码]

Get a connection from the pool

参数:

command_name (str)

返回类型:

Connection

get_encoder()[源代码]

Return an encoder based on encoding settings

返回类型:

Encoder

get_protocol()[源代码]
返回:

The RESP protocol version, or None if the protocol is not specified, in which case the server default will be used.

make_connection()[源代码]

Create a new connection

返回类型:

ConnectionInterface

release(connection)[源代码]

Releases the connection back to the pool

参数:

connection (Connection)

返回类型:

None

ConnectionPool (异步)

class redis.asyncio.connection.ConnectionPool(connection_class=<class 'redis.asyncio.connection.Connection'>, max_connections=None, **connection_kwargs)[源代码]

Create a connection pool. If max_connections is set, then this object raises ConnectionError when the pool's limit is reached.

By default, TCP connections are created unless connection_class is specified. Use UnixDomainSocketConnection for unix sockets.

Any additional keyword arguments are passed to the constructor of connection_class.

参数:
  • connection_class (Type[AbstractConnection])

  • max_connections (int | None)

async aclose()[源代码]

Close the pool, disconnecting all connections

返回类型:

None

can_get_connection()[源代码]

Return True if a connection can be retrieved from the pool.

返回类型:

bool

async disconnect(inuse_connections=True)[源代码]

Disconnects connections in the pool

If inuse_connections is True, disconnect connections that are current in use, potentially by other tasks. Otherwise only disconnect connections that are idle in the pool.

参数:

inuse_connections (bool)

async ensure_connection(connection)[源代码]

Ensure that the connection object is connected and valid

参数:

connection (AbstractConnection)

classmethod from_url(url, **kwargs)[源代码]

Return a connection pool configured from the given URL.

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0

  2. If using the redis:// or rediss:// schemes, the path argument

    of the url, e.g. redis://localhost/0

  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values "True"/"False" or "Yes"/"No". Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool's class initializer. In the case of conflicting arguments, querystring arguments always win.

参数:

url (str)

返回类型:

_CP

get_available_connection()[源代码]

Get a connection from the pool, without making sure it is connected

async get_connection(command_name, *keys, **options)[源代码]

Get a connected connection from the pool

get_encoder()[源代码]

Return an encoder based on encoding settings

make_connection()[源代码]

Create a new connection. Can be overridden by child classes.

async release(connection)[源代码]

Releases the connection back to the pool

参数:

connection (AbstractConnection)