Search code examples
rustredisconnectionrust-cargo

Redis Pub/Sub in Rust: Message Not Received


I am attempting to send data through channel creation using Redis pub/sub. The issue is that the message is not being received, even if it is published. What am I doing wrong in this? And how can I correct it? I am a novice in Rust.

use redis::{Client, Commands, RedisError};

#[tokio::main]
async fn main() -> Result<(), RedisError> {
    // Connect to Redis
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let mut con = client.get_connection()?;
    println!("Successfully connected to Redis!");
    let channel = "mychannel";
    let message = "hello";
    con.publish(channel, message)?;
    let mut pubsub = con.as_pubsub();

    pubsub.subscribe("mychannel")?;
    println!("subscribed to mychannel");

    loop {
        println!("waiting for message");
        let msg = pubsub.get_message()?;
        let payload: String = msg.get_payload()?;
        println!("Received data on mychannel: {}", payload);
    
        println!("got message");
    }


}

Solution

  • Apparently you need to subscribe before you publish message.
    Redis Pub/Sub it simply delivers the message to all current subscribers at the time of publishing.
    Try that:

    let mut pubsub = con.as_pubsub();
    pubsub.subscribe("mychannel")?;
    println!("subscribed to mychannel");
    
    // now you can publish message
    con.publish(channel, message)?;