利用redis的发布与订阅实现消息异步推送

| 阅读:829 发表时间:2018-06-09 14:20:18 Redis

<?php

ini_set('default_socket_timeout', -1); //避免在默认的配置下,1分钟后终端了与redis服务器的链接

$redis = new Redis();

$redis->connect('127.0.0.1',6379);

$redis->subscribe(['task_queue','task_hello'], function($redis,$chan,$msg){

switch ($chan) {

    case 'task_queue':

        $task = unserialize($msg);

        if($task['task']=='send_email'){

            print_r($task['data']);

        }

        break;

    case 'task_hello':

        $task = unserialize($msg);

        if($task['task']=='send_hello'){

            print_r($task['data']);

        }

        break;

    default:

        break;

}


});
<?php//taskPub.php 任务发布者

$redis = new Redis();

$redis->connect('127.0.0.1');

$task = [

'task'=>'send_email',

'data'=>"你好,隔壁老王\t\n",

];

$redis->publish('task_queue', serialize($task));

$task2 = [

'task'=>'send_hello',

'data'=>"Hello World\t\n",

];

$redis->publish('task_hello',serialize($task2));

企业微信截图_15284544358966.png\

企业微信截图_15284544573135.png


企业微信截图_15284543612089(1).png