9951 explained code solutions for 126 technologies


php-redisRedis pub/sub example


# --- publisher.php ---
ini_set('default_socket_timeout', -1);
$redis->subscribe(['chl'], function($r, $c, $m) {
  # do something with message
});

# --- subscriber.php ---
$redis->publish('chl', 'hi');ctrl + c
$redis

Redis object after connection

subscribe

subscribe to a specified channel(will wait till message arrived)

chl

channel name to subscribe/publish to

function($r, $c, $m)

callback will be called when new messages arrives

publish

publish message to specified channel

'hi'

message to publish


Usage example

<?php

$r = new Redis(); 
$r->connect('127.0.0.1', 6379); 

$r->subscribe(['chl'], function($r, $c, $m) {
  die($m);
});

# run this from different script
# $r->publish('chl', 'hi');
output
hi