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

I have to subscribe to all the channels of my Redis db and simultaneously read data from another hash in the same db node. The following is the code I have written for this using 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
    }
}

The problem here is that once I get subscribed to all the channels on db1 in Redis. I don't get any result if I try to run HGET, even though the data for the given key exists in the db. I have put additional comments in the code above to explain where the problem is. Check getNotifSettings() function.

Any help will be appreciated.

dongliang7545
dongliang7545 你能帮忙吗?
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问