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
What does your subscription code look like?
The receiving end for pub/sub with Redis should look something like this:
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.
https://laravel.com/docs/master/redis
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 runningSUBSCRIBE foo
inredis-cli
.After running
MONITOR
inredis-cli
I noticed that the published channel name is different than I expected –{app-name}_database_foo
.This is configured in
database.php
in theredis.options.prefix
key, which isenv('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
by default, knowing this / changing this will help.