0
0
Djangoframework~5 mins

Redis as message broker in Django

Choose your learning style9 modes available
Introduction

Redis as a message broker helps different parts of your app talk to each other quickly and reliably.

You want to send notifications between different parts of your Django app.
You need to handle tasks in the background without making users wait.
You want to build a chat app where messages go instantly between users.
You want to connect multiple servers or services to work together smoothly.
Syntax
Django
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.publish('channel_name', 'message')

pubsub = r.pubsub()
pubsub.subscribe('channel_name')
for message in pubsub.listen():
    print(message)

Use publish to send messages to a channel.

Use subscribe to listen for messages on a channel.

Examples
This sends the message 'Hello everyone!' to the 'chat' channel.
Django
r.publish('chat', 'Hello everyone!')
This listens to the 'chat' channel and prints any new messages.
Django
pubsub.subscribe('chat')
for msg in pubsub.listen():
    print(msg)
Sample Program

This Django-friendly Python script uses Redis to send and receive messages on the 'notifications' channel. It starts a listener in the background that prints any received messages. Then it sends three notifications one by one with a pause.

Django
import redis
import threading
import time

r = redis.Redis(host='localhost', port=6379, db=0)

# Function to listen for messages

def listen():
    pubsub = r.pubsub()
    pubsub.subscribe('notifications')
    for message in pubsub.listen():
        if message['type'] == 'message':
            print(f"Received: {message['data'].decode()}")

# Start listener in a separate thread
listener_thread = threading.Thread(target=listen, daemon=True)
listener_thread.start()

# Simulate sending messages
for i in range(3):
    msg = f"Notification {i+1}"
    r.publish('notifications', msg)
    print(f"Sent: {msg}")
    time.sleep(1)
OutputSuccess
Important Notes

Make sure Redis server is running on your machine before running the code.

Use decoding like message['data'].decode() to convert bytes to string.

Running the listener in a separate thread helps your app keep working while waiting for messages.

Summary

Redis can send messages between parts of your Django app fast and easily.

Use publish to send and subscribe to receive messages.

Running listeners in background threads keeps your app responsive.