php redis发布订阅的使用
简介
Redis提供了基于“发布/订阅”模式的消息机制。此种模式下,消息发布者和订阅者不进行直接通信,发布者客户端向指定的频道(channel) 发布消息,订阅该频道的每个客户端都可以收到该消息。Redis提供了若干命令支持该功能,在实际应用开发时,能够为此类问题提供实现方法。
使用场景
- 业务解耦
- 异步处理
php使用
private function pub(){$this->redis->publish('chan-1','this is a message by chan1');$this->redis->publish('chan-2','this is a message by chan2111111111111111');}private function sub(){while(true){try {if(null === $this->redis){$this->redis = (new Connect())->redis;$this->output->writeln("Redis reconnection ");}$this->redis->subscribe(['chan-1', 'chan-2'], [$this,'task']); // 第一个参数为订阅哪个频道,第二个参数为响应回调函数名称}catch (\Throwable $e){$this->output->writeln(date("Y-m-d H:i:s").",error:".$e->getMessage());$this->output->writeln("redis reconnected 10 seconds later");$this->redis = null;sleep(10);}}}public function task($instance, $channelName, $message){switch($channelName) {case 'chan-1':var_dump('chan-1'.$message);break;case 'chan-2':var_dump('chan-2'.$message);break;}}
效果


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
