<?php/** * Class Rpt redis 用于报表的缓存基本存储和读写 2.0 * @simple * Rpt::read("diamond.account",$nick); * Rpt::readSync("diamond.account",$nick); * $finder = Rpt::createFinder("diamond.account",$nick); * $finder->read(); * $finder->readSync(); * * Rpt::save("diamond.account",$nick,$data); * $storage = Rpt::createStorage("diamond.account",$nick); * $storage->save($data); * $storage->save($data,7200); */class Rpt { public static function read($key,$nick){ $finder = self::createFinder($key,$nick); return $finder->read(); } public static function readSync($key,$nick){ $finder = self::createFinder($key,$nick); return $finder->readSync(); } public static function createFinder($key,$nick){ $key = RptGenerate::key($key,$nick); return new RptFinder($key); } public static function createStorage($key,$nick){ $key = RptGenerate::key($key,$nick); return new RptStorage($key); } public static function save($key,$nick,$data,$expired=7200){ $storage = self::createStorage($key,$nick); return $storage->save($data,$expired); } public static function createRedis(){ $redis = new Redis(); $redis->connect(Yii::app()->params["RedisServerIP"]); return $redis; }}/** * Class RptFinder 数据读取 */class RptFinder { /** * @var string $key */ public $key; /** * @param string $key */ public function __construct($key){ $this->key = $key; } /** * 非安全读取数据 * @return mixed */ public function read(){ $data = $this->readData(); if($data->isRead && !$data->isExpired()) return $data->data; return null; } protected function readData(){ $redis = Rpt::createRedis(); $rptData = new RptData(); $data = json_decode($redis->get($this->key)); if(false == $data){ $rptData->isRead = false; $rptData->expiredTime = time(); $rptData->expired = 24*3600; }else{ $rptData->expired = $data->expired; $rptData->isRead = $data->isRead; $rptData->expiredTime = $data->expiredTime; $rptData->data = $data->data; } return $rptData; } /** * 同步读取数据 * @return mixed */ public function readSync(){ while(true){ $rptData = $this->readData(); if($rptData->isRead && !$rptData->isExpired()) return $this->read(); sleep(1); } }}/** * Class RptStorage 数据存储 */class RptStorage { /** * @var string key */ public $key; /** * @param string $key */ public function __construct($key){ $this->key = $key; } /** * 写入数据 * @param $data * @param int $expired * @return bool */ public function save($data,$expired=7200){ $rptData = new RptData(); $rptData->data = $data; $rptData->expiredTime = time(); $rptData->isRead = true; $rptData->expired = $expired; $redis = Rpt::createRedis(); return $redis->setex($this->key, $rptData->expired,json_encode($rptData)); }}/** * Class RptData redis存储数据实体 */class RptData { public $expired; public $expiredTime; public $data; public $isRead; public function isExpired(){ if(time()-$this->expiredTime > $this->expired) return true; return false; }}/** * Class RptGenerate key生成 */class RptGenerate { public static function key($key,$nick){ return $key.".".md5($nick); }}