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);