同时使用php-redis从redis通道订阅和读取数据

时间:2016-02-06 13:58:43

标签: php redis phpredis

我必须订阅我的Redis数据库的所有通道,同时从同一数据库节点中的另一个哈希读取数据。以下是我使用phpredis编写的代码:

$notif = new Worker;

try {
    // connect redis
    $notif->connectRedisServer();

    // start the worker processing
    $notif->startWorkerProcess();
}
catch(Exception $e) {
    exit('Exception: '.$e->getMessage());
}

class Worker {

    private $redis;

    public $recentHash         = 'tracker.data.recent';
    public $notifHash          = 'tracker.settings.data';

    public $serverConnectionDetails = { //Redis server connection details
                                    };

    private $redis;

    // redis database used for getting recent record of every imei
    const RECENTDATA_DB = 1;

    public function connectRedisServer() {
        if(!empty($this->redis))
            return $this->redis; // already connected

        $this->redis = new Redis();

        if(!$this->redis->pconnect(
            $this->serverConnectionDetails['redis']['host'],
            $this->serverConnectionDetails['redis']['port']
        ))
            return 'Redis connection failed.';

        if(isset($this->serverConnectionDetails['redis']['password'])
            &&
           !$this->redis->auth($this->serverConnectionDetails['redis']['password'])
    )
            return 'Redis authentication failed.';

        return $this->redis;
    }

    public function startWorkerProcess() {                      
        $this->redis->select(self::RECENTDATA_DB);

        $this->redis->pSubscribe(array('*'), array($this, 'processRedisData'));
    }

    public function processRedisData($redis, $pattern, $chan, $msg) {
        $message     = rtrim((string) $msg,",");

        $tData       = json_decode($message, true);

        $tId         = (int) $tData['tID'];

        echo "Recent Published Data:";
        var_dump($tData);

        $data = $this->getNotifSettings($tId);

        if(!empty($data)) {
            echo "Redis Settings: ";
            var_dump($trackerSettings);
        }       
   }

    public function getNotifSettings($tId) {
        $data = $this->redis->hGet($this->notifHash, $tId); //This command doesn't return any data even if it exists for the $tId

        if($data === false)
            return null;

        $data = json_decode($data, true);

        return $data; // Always comes up as null
    }
}

这里的问题是,一旦我订阅了Redis中db1上的所有频道。如果我尝试运行HGET,我将无法获得任何结果,即使数据库中存在给定密钥的数据也是如此。我在上面的代码中添加了其他注释来解释问题所在。检查getNotifSettings()功能。

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题