Implementing Pub/Sub for Notifications

Welcome! In this unit, we will delve into implementing Pub/Sub for notifications within our Redis-based backend system project. You've already learned how to manage user data, handle transactions, and use streams for event logging. Now, we'll add another powerful feature to our project: real-time notifications using Redis Pub/Sub (publish/subscribe). This will enable our system to send and receive messages instantaneously.

What You'll Build

In this unit, we'll focus on creating a simple real-time notification system using Redis Pub/Sub. Specifically, we'll cover:

  1. Publishing Messages: How to send notifications.
  2. Subscribing to Channels: How to receive and handle notifications.

Here is a quick refresh of how Pub/Sub works in Redis:

import redis
import json
import redis
import time

# Connect to Redis
client = redis.Redis(host='localhost', port=6379, db=0)

# Function to publish messages to a channel
def publish_message(channel, message):
    client.publish(channel, json.dumps(message))

# Function to handle incoming messages
def message_handler(message):
    data = json.loads(message['data'])
    print(f"Received message from {data['user']}: {data['text']}")

# Function to subscribe to a channel
def subscribe_to_channel(channel):
    pubsub = client.pubsub()
    pubsub.subscribe(**{channel: message_handler})
    return pubsub.run_in_thread(sleep_time=0.001)

# Example usage
channel_name = 'chat_room'
thread = subscribe_to_channel(channel_name)

message = {'user': 'alice', 'text': 'Hello everyone!'}
publish_message('chat_room', message)

# Giving some time for the subscription to set up
time.sleep(1)
thread.stop()

In this snippet, message_handler processes incoming messages on the chat_room channel. The subscribe_to_channel function sets up the subscription and runs it in a separate thread. The publish_message function sends a message to the specified channel, which is then received by the message_handler and printed to the console.

Exciting, isn’t it? Now, it's time to put this into practice. Let's implement the complete code to build our real-time notification system.

Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal