redis subscribe and publish

Test with php

Test code

<?php

count($argv) > 1 && $type = $argv[1];
if ( $type == 'subscribe' ) {
    echo "subscribe\n";
    
    $redis = new Redis();
    $redis->connect('127.0.0.1', '6379');
    $redis->subscribe(['order', 'storage'], function ($redis, $channel, $message) {
        var_dump($redis);
        if ( $channel == 'order' ) {
            var_dump($channel);
            print_r(json_decode($message, true));
        } else {
            sleep(1);
            var_dump($channel);
            print_r(json_decode($message, true));
        }
    });
    $redis->close();

}elseif ( $type == 'publish' ) {
    echo "publish\n";
    
    $order = [
        'id' => 1,
        'name' => 'iphone 8',
        'price' => 5600,
        'create_time' => '2019-05-21',
    ];
    
    $redis = new Redis();
    $redis->connect('127.0.0.1', '6379');
    for ($i = 1; $i <= 10; $i++ ) {
        $order['id'] = $i;
        $redis->publish("order", json_encode($order));
        $storage = $order;
        $storage['storage'] = 10-$i;
        $redis->publish("storage", json_encode($storage));
    }
    $redis->close();

}else {
    echo 'wrong\n';
}

Exec

Open one comand terminal window exec

$ php subscribe_publist.php subscribe

Oen another comand terminal window exec

php subscribe_publist.php publish

Back first terminal (subscribe window) info

subscribe
object(Redis)#1 (0) {
}
string(5) "order"
Array
(
    [id] => 1
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
)
object(Redis)#1 (0) {
}
string(7) "storage"
Array
(
    [id] => 1
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
    [storage] => 2
)
object(Redis)#1 (0) {
}
string(5) "order"
Array
(
    [id] => 2
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
)
object(Redis)#1 (0) {
}
string(7) "storage"
Array
(
    [id] => 2
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
    [storage] => 1
)
object(Redis)#1 (0) {
}
string(5) "order"
Array
(
    [id] => 3
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
)
object(Redis)#1 (0) {
}
string(7) "storage"
Array
(
    [id] => 3
    [name] => iphone 8
    [price] => 5600
    [create_time] => 2019-05-21
    [storage] => 0
)

Reference

https://www.redis.net.cn/tutorial/3514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值