skip to Main Content

I am using laravel api as a backend and vue as a front end. These are standalone projects. When I am hitting the api which publishes after redis connection like

$redis = Redis::connection();

$redis->publish('new_message_sent',json_encode($request->all()));

It does not do anything. Infact when I hit the api (using postman) and return the $redis object, it returns me an empty object.

Here is the node server code for subscription

io.on("connection", function(socket) {
   console.log("Client Connecteddddd");
   var redisClient = redis.createClient();
   redisClient.subscribe("new_message_sent");


   redisClient.on("new_message_sent", function(channel, message) {
       message = JSON.parse(message);
       console.log(message);    
   });

   redisClient.on("disconnect", function() {
       redisClient.quit();
   });
});

2

Answers


  1. What does your subscription code look like?

    The receiving end for pub/sub with Redis should look something like this:

      Redis::subscribe(['your-channel'], function ($message) {
                echo $message;
            });
    

    This would be a long running process. This would run and echo anything that is published to ‘your-channel’ until something interrupts it.

    If you aspire to get the information to the browser for an end user, you will need an extra step such as a websocket.

    The nature of pub/sub means it would never be aware of messages send before the subscribe() happens, only those that happen while it is running.

    For publishing, you shouldn’t need to resolve the connection first.

    Redis::publish('new_message_sent', json_encode($request->all()));
    

    https://laravel.com/docs/master/redis

    Login or Signup to reply.
  2. I’ve stumbled on a similar situation where I’d expect my Redis client to receive the published message from Laravel’s Redis Facade but it didn’t.

    I expected Redis::publish('foo', 'bar') to be picked up when running SUBSCRIBE foo in redis-cli.

    After running MONITOR in redis-cli I noticed that the published channel name is different than I expected – {app-name}_database_foo.

    This is configured in database.php in the redis.options.prefix key, which is env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), by default, knowing this / changing this will help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search