Chen
Chen

Reputation: 31

set was executed successfully in redis but get nothing

I'm using phpredis in my program, store something in the redis server, get them when the same request comes(in the same day), but I always get empty result. Can anyone give me some enlightenment? Here is the code of Cache class I'm using:

<?php
class Cache
{
    public static function getInstance()
    {
        static $instance = null;
        null == $instance && $instance = new self();
        return $instance;
    }

    protected function __construct()
    {
    }

    protected function getR()
    {
        static $r = NULL;
        if (NULL == $r) {
            $r = new Redis();
            try {
                $r->pconnect(HOST, PORT, 5);
            } catch(Exception $ex) {
                //log
                try {
                    $api->connect(HOST, PORT, 5);
                } catch (Exception $ex) {
                    //log
                }
            }
        }

        return $r;
    }

    public function getValue($key)
    {
        $result = array();
        $r = $this->getR();
        if(!empty($r)) {
            try{
                $result = $r->hKeys($key);
                $r->setTimeout($keys, 86400);
            } catch (Exception $ex){
                //log
            }
        }

        return $result; // return true
    }

    public function setValue($key, $value)
    {
        $result = false;
        $r = $this->getR();
        if(!empty($r)) {
            try{
                $result = $r->hMset($key, $value);
            } catch (Exception $ex){
                //log
            }
        }
    }
}
?>

EDIT:
I checked the key-values with redis-cli, found something wired: the key-value data was stored in db 5 while I thought it should be in DB 0 by default without select statement, but the program retrieved db 0, of course nothing returned. Now I'm wondering why the data went to DB 5 given that I've not selected DB.

Upvotes: 1

Views: 2267

Answers (1)

Chen
Chen

Reputation: 31

Finally, I've figured out what happend here. Before I stored my key–value pair, there was some code which also had communicated with Redis server and it had explicitly selected the DB 5, and the default DB of my redis connection was affected by last context, so my data was stored in DB 5. By coincidence, when I wanted to retrive my data, the last redis connection used DB 0, of course I got nothing.

Upvotes: 2

Related Questions