Redis Cluster¶
If your infrastructure contains a Redis Cluster, coredis provides
a coredis.RedisCluster
client than can be used with the same API
as coredis.Redis
but with awareness of distributing the operations
to the appropriate shards.
For operations that operate on single keys the client simply routes the command to the appropriate node.
There are, however a few other categories of operations that cannot simply be used with redis cluster by just routing it to the appropriate node. The API docs will call out any exceptional handling that coredis performs to allow application developers to use the APIs transparently when possible.
Examples of such APIs are:
- async RedisCluster.exists(keys: Parameters[KeyT]) int
Determine if a key exists
- Returns:
the number of keys that exist from those specified as arguments.
Redis command documentation: EXISTS
Cluster note
The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slot
toFalse
- async RedisCluster.delete(keys: Parameters[KeyT]) int
Delete one or more keys specified by
keys
- Returns:
The number of keys that were removed.
Redis command documentation: DEL
Cluster note
The command will be run on all primaries by distributing the keys to the appropriate nodes and return the sum of results.
To disable this behavior set
RedisCluster.non_atomic_cross_slot
toFalse
- async RedisCluster.script_load(script: StringT) AnyStr
Loads a Lua
script
into the script cache.- Returns:
The SHA1 digest of the script added into the script cache
Redis command documentation: SCRIPT LOAD
Cluster note
The command will be run on all nodes and return the response from any shard if all responses are consistent
Replication¶
coredis supports ensuring synchronous replication of writes using the WAIT
command. This is abstracted away with the ensure_replication()
context manager.
The following example will ensure that the SET is replicated to atleast 2 replicas within 100 milliseconds (default
value of timeout_ms
),
else raise a ReplicationError
:
import asyncio
import coredis
async def test():
client = coredis.RedisCluster("localhost", 7000)
with client.ensure_replication(replicas=2):
await client.set("fubar", 1)
asyncio.run(test())