redis類與用法
<?php
namespace app\common\model;
class Cache
{
public $redis = null;
public function __construct() {
if (is_null($this->redis)) {
$this->redis = new \Redis();
$this->redis->connect(‘127.0.0.1‘, ‘6379‘);
}
}
//獲取對應緩存
//subkey = ‘s‘
public function get_obj_cache($key = ‘‘, $subkey = ‘‘)
{
$data = false;
$key = (string)$key;
$subkey = (string)$subkey;
// 檢查變量
if (!is_not_empty_string($key))
{
return $data;
}
// 讀取數據
if (is_not_empty_string($subkey) && $subkey == ‘s‘)
{
$data = $this->redis->smembers($key);
if(is_not_empty_array($data)) return $data;
return false;
}
else
{
$data = $this->redis->get($key);
}
return $data;
}
//刪除對應緩存
public function cache_del ( $key = ‘‘) {
$state = false;
// 檢查變量
if ( !is_not_empty_string( $key ))
{
return $state;
}
// 刪除數據
$this->redis->del($key);
$state = true;
return $state;
}
//更新對應緩存 key_val
public function cache_item($key = ‘‘, $value = ‘‘, $cache_time = 0)
{
$state = false;
// 檢查參數
if ( !is_not_empty_string( $key ))
{
return $state;
}
// 存儲數據
$this->redis->set($key, $value);
// 設置過期時間
if ($cache_time > 0) {
$this->redis->expire($key, (int)$cache_time);
}
$state = true;
return $state;
}
//更新對應集合key
public function cache_Sitem ($key = ‘‘, $value = ‘‘) {
$state = false;
// 檢查參數
if (!is_not_empty_string($key) || empty($value))
{
return $state;
}
// 存儲數據
$this->redis->sadd($key, $value);
$state = true;
return $state;
}
//移除集合元素
public function ceche_Sremove ($key = ‘‘, $value = ‘‘) {
$state = false;
$key = (string)$key;
// 檢查參數
if (!is_not_empty_string($key))
{
return $state;
}
// 移除元素
$this->redis->srem($key, $value);
$state = true;
return $state;
}
}
共用的model類使用
<?php
namespace app\index\model;
use think\Model;
use think\Request;
use think\Db;
use think\Cookie;
use app\common\model\Cache;
class Suv extends Model
{
private $Dk_User_Info_Cache_Key = ‘Dk_User_Info_Cache_Uid_%d‘; //獲取查詢的id
private $Cache_time = 604800; //默認緩存時間
public function suibian($uid = 0){
$data = [];
$Cache_obj = new Cache();
$cachekey = sprintf($this->Dk_User_Info_Cache_Key, $uid);//Dk_User_Info_Cache_Uid_1
$data = unserialize($Cache_obj -> get_obj_cache($cachekey));//讀取redis緩存,反序列化
if(false === $data){
//echo ‘kong‘;
$UserInfo = Db::table(‘mb_user‘)->where(‘UserId‘,‘1‘)->find();
if(!empty($UserInfo)){
$Cache_obj->cache_item($cachekey, serialize( $UserInfo), $this->Cache_time);//序列化後存到redis中
}
$data = $UserInfo;
}
return $data;
}
}
控制器使用公共model類
$AAA = new Suv();
$res = $AAA->suibian(1);
redis類與用法