合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] ## 队列 <details> <summary>queue.php</summary> ``` $redis = new Redis(); $redis->connect('127.0.0.1','6379'); //echo $redis->ping(); //在其他地方获存入队列 $redis->rPush("mylist", json_encode(["php", "aaa"])); $redis->rPush("mylist", "python"); $redis->rPush("mylist", "go"); while(true){ //获取弹出一个 //判断长度大于10 个执行一次 $range = $redis->lRange('mylist', 0, -1); if(count($range)>=10){ foreach(range(0 , 10) as $v){ $res =$redis->lPop('mylist'); echo $res; } }else{ sleep(1); } } ``` </details> <br /> <details> <summary>client.php</summary> ``` sleep(2); $redis = new Redis(); $redis->connect('127.0.0.1','6379'); //在其他地方获存入队列 $redis->rPush("mylist", json_encode(["php", "aaa"])); $redis->rPush("mylist", "python"); $redis->rPush("mylist", "go"); $redis->rPush("mylist", "go"); $redis->rPush("mylist", "go"); $redis->rPush("mylist", "go"); $redis->rPush("mylist", "go"); $redis->rPush("mylist", "go"); ``` </details> <br /> 运行 ``` $ php queue.php $ php client.php ``` ## 订阅发布 server.php ``` $redis = new Redis(); if ( ! $redis->connect('127.0.0.1', 6379)) { die($redis->getLastError()); } $redis->publish("chat", "123"); ``` client.php ``` $redis = new Redis(); if ( ! $redis->connect('127.0.0.1', 6379)) { die($redis->getLastError()); } $redis->set("count", "1"); print_r($redis->get("count")); function f($redis, $chan, $msg) { switch($chan) { case 'chat': print_r($msg); break; case 'chan-2': break; case 'chan-2': break; } } while (true){ $redis->subscribe(array('chat', 'chan-2', 'chan-3'), 'f'); // subscribe to 3 chans sleep(1); } ``` ``` php client.php php server.php ```