/** * 设置一个hash数组 * @param string $key * @param array $hash * @param int $expire */ public static function setHash($key, $hash, $expire = 0) { self::$instance->hmset($key, $hash); if (ctype_digit((string) $expire) && $expire) { self::$instance->expire($key, $expire); } return true; }
/** * 构造方法,根据不同的引擎传入配置信息数组 * @param array $config * @return null */ private function __construct($config = array()) { self::$ip = self::get_client_ip(); self::$watchType = isset($config['type']) ? $config['type'] : 'number'; if (class_exists('Redis') && isset($config['mode']) && $config['mode'] == 'redis') { self::$kv = new RedisCache(); $redis_config = array('host' => isset($config['host']) ? $config['host'] : '127.0.0.1', 'port' => isset($config['port']) ? $config['port'] : 6379, 'auth' => isset($config['auth']) ? $config['auth'] : ''); self::$kv->connect($redis_config); // 如果设置了记录间隔时间则判断$key是否需要清除 if (isset($config['interval'])) { // redis的kv类型直接使用ttl获取过期时间,expire设置过期时间 if (self::$watchType == 'number') { // 查看是否已经设置了过期时间 $ttl = self::$kv->ttl(self::$ip); self::$kv->expire(self::$ip, $config['interval']); } else { // redis的list类型需要获取尾部最后一次请求的时间与当前时间做比对以判断是否过期 $first = self::$kv->lget(self::$ip, -1); if ($first && $first + $config['interval'] < time()) { self::$kv->delete(self::$ip); } } } } else { // 文件缓存配置 $file_config = array('file_dir' => isset($config['file_dir']) ? $config['file_dir'] : sys_get_temp_dir() . '/' . self::$watchType, 'prefix' => isset($config['prefix']) ? $config['prefix'] : '', 'suffix' => isset($config['suffix']) ? $config['suffix'] : ''); // 建立缓存目录 if (!is_dir($file_config['file_dir'])) { mkdir($file_config['file_dir'], 0777, true); } self::$kv = new FileCache($file_config); // 如果设置了记录间隔时间则判断$key是否需要清除 if (isset($config['interval'])) { $filepath = self::$kv->_path(self::$ip); // 清除缓存,通过文件的修改时间判断,如果过期则删除重新计数 clearstatcache(); if (file_exists($filepath) && filemtime($filepath) + $config['interval'] < time()) { @unlink($filepath); } } } }
/** * 设置过期时间 * * @param string $key * @param number $timeout */ public function expire($key, $timeout) { return $this->redis->expire($key, $timeout); }
/** * 设置hash cache * * @param hashKey * @param key * @param data * @param expireTime(int) * @return boolean */ public function hSet($hashKey, $key, $data, $expireTime = 3600) { $status = $this->redis->hSet($hashKey, $key, $data); $this->redis->expire($hashKey, $expireTime); return $status; }