# Create a pub/sub object
pubsub = r.pubsub()# Subscribe to a channel
pubsub.subscribe('mychannel')# Publish a message to the channel
r.publish('mychannel','Hello, world!')
实现分布式锁:使用Redis的SETNX命令实现分布式锁,可以防止多个进程同时访问共享资源。
# Acquire a lockdefacquire_lock(lockname, acquire_timeout=10):# Generate a unique identifier for the lock
identifier =str(uuid.uuid4())# Try to acquire the lock
end = time.time()+ acquire_timeout
while time.time()< end:if r.setnx(lockname, identifier):return identifier
# Wait for a short time before retrying
time.sleep(0.001)# Could not acquire the lockreturnNone# Release a lockdefrelease_lock(lockname, identifier):# Check if the lock is still held by the current processif r.get(lockname)== identifier:# Release the lock
r.delete(lockname)