Redis®*: Using Pub/Sub with Redis and Python
This documentation is part of the Using with Python guide. You can view the complete guide here: How to connect Redis with Python.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Redis cloud solution that provides numerous benefits, including:
Redis Commanderweb UI included.- Unlimited message size and transfers.
- Simplified updates with just a click.
- Optimal performance and enhanced security powered by a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Redis cloud hosting solution!
Redis' Publish/Subscribe feature can be easily utilised with Python. Here is a simple example to guide you:
import redis
# Connect to Redis
r = redis.from_url(
'rediss://default:<password>@<XXXXXX>.stackhero-network.com:<PORT_TLS>',
health_check_interval=10,
socket_connect_timeout=5,
socket_keepalive=True,
retry_on_timeout=True
)
# Create a PubSub instance
p = r.pubsub()
# Subscribe to the channel "test"
p.subscribe('test')
# Publish a message to the channel "test"
r.publish('test', 'This is a test message')
# Get the first available message from channel "test"
p.get_message()
# Unsubscribe from channel "test"
p.unsubscribe('test')