我使用PHP来使用Redis进行备忘录

处理速度验证部分(2015年6月4日附注)

使用哈希存储数据时,与具有相同数据结构的MySQL相比,数据获取速度如何?

在需要获取多个数据时,使用”select field from db_table where id=’key'”语句比使用”$redis->hGet(‘key’,’field’)”更高效,但Redis在单独获取数据方面更快。

for($i=0;$i<100;$i++){
    $redis->hGet($key,'field');
}

如果是这种模式的话

select `field` from user_data where uid>=0 and uid<100;

速度更快。


到期日期:2015年6月3日 (更新)


在Github上看了一下phpredis,似乎没有像expire()的方法存在?

$redis->set('x', '42');
$redis->setTimeout('x', 3); // x will disappear in 3 seconds.

The phrase “とか” can be paraphrased in Chinese as “之类的” (zhī lè de).

$redis->set('x', '42');
$now = time(NULL); // current timestamp
$redis->expireAt('x', $now + 3);    // x will disappear in 3 seconds.

似乎提供了像这样的方法。(未经测试)
setTimeout()需要注意的是单位不是毫秒,而是“秒”。
expireAt()似乎很方便,可以指定UNIX时间。比如设置到今天的24点,非常简单。


散列类型的编码


主要便利上我们称之为“HASH”键,不能在末尾使用数字。
需要使用冒号夹在键和数字之间,就像’key:1’一样,似乎是必要的。

$redis->hSet('key1','mykey','test');//false

看起来副键(字段?)是可以使用的。

$redis->hSet('key','mykey1','test');//true

连接的重复使用

or

连接的多次应用

class RedisManager extends Redis{
    public function __construct($is_master,$db_number=0) {
        if($is_master){
            parent::__construct();
            $this->pconnect(Conf::$redis_m_host,Conf::$redis_m_port);
            $this->select($db_number);
        }else{
            parent::__construct();
            $this->pconnect(Conf::$redis_s_host,Conf::$redis_s_port);
            $this->select($db_number);
        }
        return $this;
    }
}

虽然这个源有很多可以挑剔的地方,但我想要做的是

1. 新建立连接时,我想要直接选择数据库。
2. 可能会在一次处理中多次新建连接,所以想要重复利用连接。(一次处理中不能开启多个连接…对吧?)

上述的代码产生了错误,据说是因为Redis服务器断开连接了。

由于没有高超的技巧,因此如下所示

class RedisManager extends Redis{
    private $is_master;
    private $is_connected = false;
    public $db_number;

    public function __construct($is_master,$db_number=0) { //オーバーライド
        $this->is_master = $is_master;
        $this->db_number = $db_number;
        if($is_master){
            parent::__construct();
        }else{
            parent::__construct();
        }
        return $this;
    }

    public function connect() { //オーバーライド
        if(!$this->is_connected){
            if($this->is_master){
                parent::connect(Conf::$redis_m_host,Conf::$redis_m_port);
                parent::select($this->db_number);
                $this->is_connected = true;
            }else{
                parent::connect(Conf::$redis_s_host,Conf::$redis_s_port);
                parent::select($this->db_number);
                $this->is_connected = true;
            }
        }
        return $this;
    }
}

当你使用时

$redis_master = new RedisManager(true); //こんな感じでnewしておいて

$redis_master->connect()->hGet('aaa','bbb');
$redis_master->connect()->hGet('xxx','yyy'); //こんな感じで使います。

这样使用多次也不会出错。

广告
将在 10 秒后关闭
bannerAds