126 lines
2.9 KiB
PHP
126 lines
2.9 KiB
PHP
<?php
|
|
/**
|
|
* Created by PhpStorm.
|
|
* User: zn
|
|
* Date: 2017/6/26
|
|
* Time: 19:04
|
|
*/
|
|
|
|
namespace common\utils;
|
|
|
|
|
|
use RedisClient\Client\AbstractRedisClient;
|
|
use RedisClient\ClientFactory;
|
|
use RedisClient\RedisClient;
|
|
use yii\base\Object;
|
|
use yii\db\ActiveRecord;
|
|
|
|
/**
|
|
* redis
|
|
* Class RedisClientComp
|
|
* @package common\utils
|
|
*/
|
|
class RedisClientComp extends Object
|
|
{
|
|
private $_redis = null;
|
|
|
|
/**
|
|
* @var string[]
|
|
*/
|
|
private $_keyList = [];
|
|
|
|
/**
|
|
* @return RedisClient
|
|
*/
|
|
public function instance()
|
|
{
|
|
if (empty($this->_redis)) {
|
|
//server
|
|
$paramServer = (string)YiiComponentUtil::getParam('redis_server');
|
|
if (empty($paramServer)) $paramServer = '127.0.0.1';
|
|
|
|
//port
|
|
$paramPort = (int)YiiComponentUtil::getParam('redis_port');
|
|
if (empty($paramPort)) $paramPort = 6379;
|
|
|
|
$config[AbstractRedisClient::CONFIG_SERVER] = sprintf('%s:%d', $paramServer, $paramPort);
|
|
|
|
//password
|
|
$paramPassword = (string)YiiComponentUtil::getParam('redis_password');
|
|
$paramPassword = trim($paramPassword);
|
|
if (!empty($paramPassword)) $config[AbstractRedisClient::CONFIG_PASSWORD] = $paramPassword;
|
|
|
|
$this->_redis = ClientFactory::create($config);
|
|
}
|
|
|
|
return $this->_redis;
|
|
}
|
|
|
|
public function get($key)
|
|
{
|
|
return $this->instance()->get($key);
|
|
}
|
|
|
|
public function set($key, $value, $seconds = null, $milliseconds = null, $exist = null)
|
|
{
|
|
$this->addDirtyKey($key);
|
|
return $this->instance()->set($key, $value, $seconds, $milliseconds, $exist);
|
|
}
|
|
|
|
public function del($keys)
|
|
{
|
|
return $this->instance()->del($keys);
|
|
}
|
|
|
|
/**
|
|
* @param string $pKey
|
|
*/
|
|
public function addDirtyKey($pKey)
|
|
{
|
|
if (empty($pKey)) return;
|
|
array_push($this->_keyList, $pKey);
|
|
}
|
|
|
|
/**
|
|
* 删除脏数据
|
|
*/
|
|
public function clearDirtyKey()
|
|
{
|
|
if (count($this->_keyList) > 0) $this->instance()->del($this->_keyList);
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @param ActiveRecord $model
|
|
* @return bool
|
|
*/
|
|
public function modelSaveToRedis($key, $model)
|
|
{
|
|
if (empty($key) || empty($model)) return false;
|
|
|
|
$jsonStr = json_encode($model->toArray());
|
|
if (empty($jsonStr)) return false;
|
|
|
|
return $this->set($key, $jsonStr, YiiComponentUtil::getParam('redis_cache_time'));
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @param ActiveRecord & $model
|
|
* @return bool
|
|
*/
|
|
public function modelLoadFromRedis($key, &$model)
|
|
{
|
|
$jsonStr = $this->get($key);
|
|
|
|
if (empty($jsonStr)) return false;
|
|
|
|
$jsonData = json_decode($jsonStr, true);
|
|
if (empty($jsonData)) return false;
|
|
|
|
$model->setAttributes($jsonData, true);
|
|
$model->setIsNewRecord(false);
|
|
|
|
return true;
|
|
}
|
|
} |