您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
workerman-redis組件 -pSubscribe
发布时间:2021-12-25 19:32:20编辑:雪饮阅读()
pSubscribe
订阅一个或多个符合给定模式的频道。
每个模式以 * 作为匹配符,比如 it* 匹配所有以 it 开头的频道( it.news 、 it.blog 、 it.tweets 等等)。 news.* 匹配所有以 news. 开头的频道( news.it 、 news.global.today 等等),诸如此类。
注意:pSubscribe回调函数有4个参数($pattern, $channel, $message, $redis)
当$redis实例调用pSubscribe或subscribe接口后,当前实例再调用其它方法将被忽略。(就很坑)
實例:
<?php
use Workerman\Worker;
use Workerman\Redis\Client;
use Workerman\Connection\TcpConnection;
use Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('http://0.0.0.0:6161');
$worker->onWorkerStart = function() {
};
$worker->onMessage = function(TcpConnection $connection, $data) {
$redis = new Client('redis://127.0.0.1:6379');
$redis->auth('xy220807', function ($result) {
var_dump($result);
});
$redis2 = new Client('redis://127.0.0.1:6379');
$redis2->auth('xy220807', function ($result) {
var_dump($result);
});
$redis->psubscribe(['news*', 'blog*'], function ($pattern, $channel, $message) use($connection) {
$str="$pattern, $channel, $message"; // news*, news.add, news content
$connection->send($str);
});
Timer::add(5, function () use ($redis2){
$redis2->publish('news.add', 'news content');
});
};
Worker::runAll();
實例運行並有http客戶端訪問時:
[root@localhost www.fpm.com]# /usr/local/php734/bin/php channelServer.php start
Workerman[channelServer.php] start in DEBUG mode
----------------------------------------- WORKERMAN -----------------------------------------
Workerman version:4.0.22 PHP version:7.3.4
------------------------------------------ WORKERS ------------------------------------------
proto user worker listen processes status
tcp root none http://0.0.0.0:6161 1 [OK]
---------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
bool(true)
bool(true)
http客戶端訪問:
[root@localhost ~]# elinks http://127.0.0.1:6161 --dump
news*, news.add, news content
关键字词:workerman,redis,pSubscribe