初始化项目

This commit is contained in:
2016-06-21 17:12:08 +08:00
commit 7ea154d684
903 changed files with 226100 additions and 0 deletions

94
core/library/think/cache/driver/Apc.php vendored Normal file
View File

@@ -0,0 +1,94 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* Apc缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Apc
{
protected $options = [
'expire' => 0,
'prefix' => '',
];
/*****************************
需要支持apc_cli模式
******************************/
/**
* 架构函数
* @param array $options 缓存参数
* @throws Exception
* @access public
*/
public function __construct($options = [])
{
if (!function_exists('apc_cache_info')) {
throw new \BadFunctionCallException('not support: Apc');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
return apc_fetch($this->options['prefix'] . $name);
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return bool
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
return apc_store($name, $value, $expire);
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return bool|\string[]
*/
public function rm($name)
{
return apc_delete($this->options['prefix'] . $name);
}
/**
* 清除缓存
* @access public
* @return bool
*/
public function clear()
{
return apc_clear_cache('user');
}
}

186
core/library/think/cache/driver/File.php vendored Normal file
View File

@@ -0,0 +1,186 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
/**
* 文件类型缓存类
* @author liu21st <liu21st@gmail.com>
*/
class File
{
protected $options = [
'expire' => 0,
'cache_subdir' => false,
'path_level' => 1,
'prefix' => '',
'path' => CACHE_PATH,
'data_compress' => false,
];
/**
* 架构函数
* @param array $options
*/
public function __construct($options = [])
{
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
if (substr($this->options['path'], -1) != '/') {
$this->options['path'] .= '/';
}
$this->init();
}
/**
* 初始化检查
* @access private
* @return boolean
*/
private function init()
{
// 创建项目缓存目录
if (!is_dir($this->options['path'])) {
if (mkdir($this->options['path'], 0755, true)) {
return true;
}
}
return false;
}
/**
* 取得变量的存储文件名
* @access private
* @param string $name 缓存变量名
* @return string
*/
private function filename($name)
{
$name = md5($name);
if ($this->options['cache_subdir']) {
// 使用子目录
$dir = '';
$len = $this->options['path_level'];
for ($i = 0; $i < $len; $i++) {
$dir .= $name{$i} . '/';
}
if (!is_dir($this->options['path'] . $dir)) {
mkdir($this->options['path'] . $dir, 0755, true);
}
$filename = $dir . $this->options['prefix'] . $name . '.php';
} else {
$filename = $this->options['prefix'] . $name . '.php';
}
return $this->options['path'] . $filename;
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$filename = $this->filename($name);
if (!is_file($filename)) {
return false;
}
$content = file_get_contents($filename);
if (false !== $content) {
$expire = (int) substr($content, 8, 12);
if (0 != $expire && time() > filemtime($filename) + $expire) {
//缓存过期删除缓存文件
$this->unlink($filename);
return false;
}
$content = substr($content, 20, -3);
if ($this->options['data_compress'] && function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
$content = unserialize($content);
return $content;
} else {
return false;
}
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
* @return boolean
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$filename = $this->filename($name);
$data = serialize($value);
if ($this->options['data_compress'] && function_exists('gzcompress')) {
//数据压缩
$data = gzcompress($data, 3);
}
$data = "<?php\n//" . sprintf('%012d', $expire) . $data . "\n?>";
$result = file_put_contents($filename, $data);
if ($result) {
clearstatcache();
return true;
} else {
return false;
}
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return $this->unlink($this->filename($name));
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
$fileLsit = (array) glob($this->options['path'] . '*');
foreach ($fileLsit as $path) {
is_file($path) && unlink($path);
}
return true;
}
/**
* 判断文件是否存在后,删除
* @param $path
* @return bool
* @author byron sampson <xiaobo.sun@qq.com>
* @return boolean
*/
private function unlink($path)
{
return is_file($path) && unlink($path);
}
}

127
core/library/think/cache/driver/Lite.php vendored Normal file
View File

@@ -0,0 +1,127 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
/**
* 文件类型缓存类
* @author liu21st <liu21st@gmail.com>
*/
class Lite
{
protected $options = [
'prefix' => '',
'path' => '',
'expire' => 0, // 等于 10*365*24*360010年
];
/**
* 架构函数
* @access public
*
* @param array $options
*/
public function __construct($options = [])
{
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
if (substr($this->options['path'], -1) != '/') {
$this->options['path'] .= '/';
}
}
/**
* 取得变量的存储文件名
* @access private
* @param string $name 缓存变量名
* @return string
*/
private function filename($name)
{
return $this->options['path'] . $this->options['prefix'] . md5($name) . '.php';
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$filename = $this->filename($name);
if (is_file($filename)) {
// 判断是否过期
$mtime = filemtime($filename);
if ($mtime < time()) {
// 清除已经过期的文件
unlink($filename);
return false;
}
return include $filename;
} else {
return false;
}
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
* @return bool
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
// 模拟永久
if (0 === $expire) {
$expire = 10 * 365 * 24 * 3600;
}
$filename = $this->filename($name);
$ret = file_put_contents($filename, ("<?php return " . var_export($value, true) . ";"));
// 通过设置修改时间实现有效期
if ($ret) {
touch($filename, time() + $expire);
}
return $ret;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return unlink($this->filename($name));
}
/**
* 清除缓存
* @access public
* @return bool
* @internal param string $name 缓存变量名
*/
public function clear()
{
$filename = $this->filename('*');
array_map("unlink", glob($filename));
}
}

View File

@@ -0,0 +1,113 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
class Memcache
{
protected $handler = null;
protected $options = [
'host' => '127.0.0.1',
'port' => 11211,
'expire' => 0,
'timeout' => 0, // 超时时间(单位:毫秒)
'persistent' => true,
'prefix' => '',
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
* @throws \BadFunctionCallException
*/
public function __construct($options = [])
{
if (!extension_loaded('memcache')) {
throw new \BadFunctionCallException('not support: memcache');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$this->handler = new \Memcache;
// 支持集群
$hosts = explode(',', $this->options['host']);
$ports = explode(',', $this->options['port']);
if (empty($ports[0])) {
$ports[0] = 11211;
}
// 建立连接
foreach ((array) $hosts as $i => $host) {
$port = isset($ports[$i]) ? $ports[$i] : $ports[0];
$this->options['timeout'] > 0 ?
$this->handler->addServer($host, $port, $this->options['persistent'], 1, $this->options['timeout']) :
$this->handler->addServer($host, $port, $this->options['persistent'], 1);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
return $this->handler->get($this->options['prefix'] . $name);
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return bool
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
if ($this->handler->set($name, $value, 0, $expire)) {
return true;
}
return false;
}
/**
* 删除缓存
* @param string $name 缓存变量名
* @param bool|false $ttl
* @return bool
*/
public function rm($name, $ttl = false)
{
$name = $this->options['prefix'] . $name;
return false === $ttl ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return bool
*/
public function clear()
{
return $this->handler->flush();
}
}

View File

@@ -0,0 +1,115 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
class Memcached
{
protected $handler = null;
protected $options = [
'host' => '127.0.0.1',
'port' => 11211,
'expire' => 0,
'timeout' => 0, // 超时时间(单位:毫秒)
'prefix' => '',
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = [])
{
if (!extension_loaded('memcached')) {
throw new \BadFunctionCallException('not support: memcached');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$this->handler = new \Memcached;
// 设置连接超时时间(单位:毫秒)
if ($this->options['timeout'] > 0) {
$this->handler->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->options['timeout']);
}
// 支持集群
$hosts = explode(',', $this->options['host']);
$ports = explode(',', $this->options['port']);
if (empty($ports[0])) {
$ports[0] = 11211;
}
// 建立连接
$servers = [];
foreach ((array) $hosts as $i => $host) {
$servers[] = [$host, (isset($ports[$i]) ? $ports[$i] : $ports[0]), 1];
}
$this->handler->addServers($servers);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
return $this->handler->get($this->options['prefix'] . $name);
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return bool
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
$expire = 0 == $expire ? 0 : time() + $expire;
if ($this->handler->set($name, $value, $expire)) {
return true;
}
return false;
}
/**
* 删除缓存
* @param string $name 缓存变量名
* @param bool|false $ttl
* @return bool
*/
public function rm($name, $ttl = false)
{
$name = $this->options['prefix'] . $name;
return false === $ttl ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return bool
*/
public function clear()
{
return $this->handler->flush();
}
}

View File

@@ -0,0 +1,128 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* Redis缓存驱动适合单机部署、有前端代理实现高可用的场景性能最好
* 有需要在业务层实现读写分离、或者使用RedisCluster的需求请使用Redisd驱动
*
* 要求安装phpredis扩展https://github.com/nicolasff/phpredis
* @author 尘缘 <130775@qq.com>
*/
class Redis
{
protected $handler = null;
protected $options = [
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = [])
{
if (!extension_loaded('redis')) {
throw new \BadFunctionCallException('not support: redis');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$func = $this->options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new \Redis;
$this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);
if ('' != $this->options['password']) {
$this->handler->auth($this->options['password']);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$value = $this->handler->get($this->options['prefix'] . $name);
$jsonData = json_decode($value, true);
// 检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 byron sampson<xiaobo.sun@qq.com>
return (null === $jsonData) ? $value : $jsonData;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return boolean
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
//对数组/对象数据进行缓存处理,保证数据完整性 byron sampson<xiaobo.sun@qq.com>
$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
if (is_int($expire) && $expire) {
$result = $this->handler->setex($name, $expire, $value);
} else {
$result = $this->handler->set($name, $value);
}
return $result;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return $this->handler->delete($this->options['prefix'] . $name);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return $this->handler->flushDB();
}
/**
* 返回句柄对象,可执行其它高级方法
*
* @access public
* @return object
*/
public function handler()
{
return $this->handler;
}
}

View File

@@ -0,0 +1,325 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\App;
use think\Cache;
use think\Exception;
use think\Log;
/**
配置参数:
'cache' => [
'type' => 'Redisd'
'host' => 'A:6379,B:6379', //redis服务器ip多台用逗号隔开读写分离开启时默认写A当A主挂时再尝试写B
'slave' => 'B:6379,C:6379', //redis服务器ip多台用逗号隔开读写分离开启时所有IP随机读其中一台挂时尝试读其它节点可以配置权重
'port' => 6379, //默认的端口号
'password' => '', //AUTH认证密码当redis服务直接暴露在外网时推荐
'timeout' => 10, //连接超时时间
'expire' => false, //默认过期时间,默认为永不过期
'prefix' => '', //缓存前缀,不宜过长
'persistent' => false, //是否长连接 false=短连接,推荐长连接
],
单例获取:
$redis = \think\Cache::connect(Config::get('cache'));
$redis->master(true)->setnx('key');
$redis->master(false)->get('key');
*/
/**
* ThinkPHP Redis简单主从实现的高可用方案
*
* 扩展依赖https://github.com/phpredis/phpredis
*
* 一主一从的实践经验
* 1, A、B为主从正常情况下A写B读通过异步同步到B或者双写性能有损失
* 2, B挂则读写均落到A
* 3, A挂则尝试升级B为主并断开主从尝试写入(要求开启slave-read-only no)
* 4, 手工恢复A并加入B的从
*
* 优化建议
* 1key不宜过长value过大时请自行压缩
* 2gzcompress在php7下有兼容问题
*
* @todo
* 1, 增加对redisCluster的兼容
* 2, 增加tp5下的单元测试
*
* @author 尘缘 <130775@qq.com>
*/
class Redisd
{
protected static $redis_rw_handler;
protected static $redis_err_pool;
protected $handler = null;
protected $options = [
'host' => '127.0.0.1',
'slave' => '',
'port' => 6379,
'password' => '',
'timeout' => 10,
'expire' => false,
'persistent' => false,
'prefix' => '',
'serialize' => \Redis::SERIALIZER_PHP,
];
/**
* 为了在单次php请求中复用redis连接第一次获取的options会被缓存第二次使用不同的$options将会无效
*
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = [])
{
if (!extension_loaded('redis')) {
throw new \BadFunctionCallException('not support: redis');
}
$this->options = $options = array_merge($this->options, $options);
$this->options['func'] = $options['persistent'] ? 'pconnect' : 'connect';
$host = explode(",", trim($this->options['host'], ","));
$host = array_map("trim", $host);
$slave = explode(",", trim($this->options['slave'], ","));
$slave = array_map("trim", $slave);
$this->options["server_slave"] = empty($slave) ? $host : $slave;
$this->options["servers"] = count($slave);
$this->options["server_master"] = array_shift($host);
$this->options["server_master_failover"] = $host;
}
/**
* 主从选择器配置多个Host则自动启用读写分离默认主写随机从读
* 随机从读的场景适合读频繁且php与redis从位于单机的架构这样可以减少网络IO
* 一致Hash适合超高可用跨网络读取且从节点较多的情况本业务不考虑该需求
*
* @access public
* @param bool $master true 默认主写
* @return Redisd
*/
public function master($master = true)
{
if (isset(self::$redis_rw_handler[$master])) {
$this->handler = self::$redis_rw_handler[$master];
return $this;
}
//如果不为主则从配置的host剔除主并随机读从失败以后再随机选择从
//另外一种方案是根据key的一致性hash选择不同的node但读写频繁的业务中可能打开大量的文件句柄
if (!$master && $this->options["servers"] > 1) {
shuffle($this->options["server_slave"]);
$host = array_shift($this->options["server_slave"]);
} else {
$host = $this->options["server_master"];
}
$this->handler = new \Redis();
$func = $this->options['func'];
$parse = parse_url($host);
$host = isset($parse['host']) ? $parse['host'] : $host;
$port = isset($parse['host']) ? $parse['port'] : $this->options['port'];
//发生错误则摘掉当前节点
try {
$result = $this->handler->$func($host, $port, $this->options['timeout']);
if (false === $result) {
$this->handler->getLastError();
}
if (null != $this->options['password']) {
$this->handler->auth($this->options['password']);
}
$this->handler->setOption(\Redis::OPT_SERIALIZER, $this->options['serialize']);
if (strlen($this->options['prefix'])) {
$this->handler->setOption(\Redis::OPT_PREFIX, $this->options['prefix']);
}
App::$debug && Log::record("[ CACHE ] INIT Redisd : {$host}:{$port} master->" . var_export($master, true), Log::ALERT);
} catch (\RedisException $e) {
//phpredis throws a RedisException object if it can't reach the Redis server.
//That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded.
//In any other problematic case that does not involve an unreachable server
//(such as a key not existing, an invalid command, etc), phpredis will return FALSE.
Log::record(sprintf("redisd->%s:%s:%s:%s", $master ? "master" : "salve", $host, $port, $e->getMessage()), Log::ALERT);
//主节点挂了以后,尝试连接主备,断开主备的主从连接进行升主
if ($master) {
if (!count($this->options["server_master_failover"])) {
throw new Exception("redisd master: no more server_master_failover. {$host}:{$port} : " . $e->getMessage());
return false;
}
$this->options["server_master"] = array_shift($this->options["server_master_failover"]);
$this->master();
Log::record(sprintf("master is down, try server_master_failover : %s", $this->options["server_master"]), Log::ERROR);
//如果是slave断开主从升主需要手工同步新主的数据到旧主上
//目前这块的逻辑未经过严格测试
//$this->handler->slaveof();
} else {
//尝试failover如果有其它节点则进行其它节点的尝试
foreach ($this->options["server_slave"] as $k => $v) {
if (trim($v) == trim($host)) {
unset($this->options["server_slave"][$k]);
}
}
//如果无可用节点,则抛出异常
if (!count($this->options["server_slave"])) {
Log::record("已无可用Redis读节点", Log::ERROR);
throw new Exception("redisd slave: no more server_slave. {$host}:{$port} : " . $e->getMessage());
return false;
} else {
Log::record("salve {$host}:{$port} is down, try another one.", Log::ALERT);
return $this->master(false);
}
}
} catch (\Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
self::$redis_rw_handler[$master] = $this->handler;
return $this;
}
/**
* 读取缓存
*
* @access public
* @param string $name 缓存key
* @param bool $master 指定主从节点,可以从主节点获取结果
* @return mixed
*/
public function get($name, $master = false)
{
$this->master($master);
try {
$value = $this->handler->get($name);
} catch (\RedisException $e) {
unset(self::$redis_rw_handler[0]);
$this->master();
return $this->get($name);
} catch (\Exception $e) {
Log::record($e->getMessage(), Log::ERROR);
}
return isset($value) ? $value : null;
}
/**
* 写入缓存
*
* @access public
* @param string $name 缓存key
* @param mixed $value 缓存value
* @param integer $expire 过期时间,单位秒
* @return boolen
*/
public function set($name, $value, $expire = null)
{
$this->master(true);
if (is_null($expire)) {
$expire = $this->options['expire'];
}
try {
if (null === $value) {
return $this->handler->delete($name);
}
if (is_int($expire) && $expire) {
$result = $this->handler->setex($name, $expire, $value);
} else {
$result = $this->handler->set($name, $value);
}
} catch (\RedisException $e) {
unset(self::$redis_rw_handler[1]);
$this->master(true);
return $this->set($name, $value, $expire);
} catch (\Exception $e) {
Log::record($e->getMessage());
}
return $result;
}
/**
* 删除缓存
*
* @access public
* @param string $name 缓存变量名
* @return boolen
*/
public function rm($name)
{
$this->master(true);
return $this->handler->delete($name);
}
/**
* 清除缓存
*
* @access public
* @return boolen
*/
public function clear()
{
$this->master(true);
return $this->handler->flushDB();
}
/**
* 返回句柄对象,可执行其它高级方法
* 需要先执行 $redis->master() 连接到 DB
*
* @access public
* @param bool $master 指定主从节点,可以从主节点获取结果
* @return \Redis
*/
public function handler($master = true)
{
$this->master($master);
return $this->handler;
}
/**
* 析构释放连接
*
* @access public
*/
public function __destruct()
{
//该方法仅在connect连接时有效
//当使用pconnect时连接会被重用连接的生命周期是fpm进程的生命周期而非一次php的执行。
//如果代码中使用pconnect close的作用仅是使当前php不能再进行redis请求但无法真正关闭redis长连接连接在后续请求中仍然会被重用直至fpm进程生命周期结束。
try {
if (method_exists($this->handler, "close")) {
$this->handler->close();
}
} catch (\Exception $e) {
}
}
}

122
core/library/think/cache/driver/Sae.php vendored Normal file
View File

@@ -0,0 +1,122 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* SAE Memcache缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Sae
{
protected $handler = null;
protected $options = [
'host' => '127.0.0.1',
'port' => 11211,
'expire' => 0,
'timeout' => false,
'persistent' => false,
'prefix' => '',
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = [])
{
if (!function_exists('memcache_init')) {
throw new \BadFunctionCallException('must run at sae');
}
$this->handler = memcache_init();
if (!$this->handler) {
throw new Exception('memcache init error');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
return $this->handler->get($_SERVER['HTTP_APPVERSION'] . '/' . $this->options['prefix'] . $name);
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return bool
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
if ($this->handler->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value, 0, $expire)) {
return true;
}
return false;
}
/**
* 删除缓存
* @param string $name 缓存变量名
* @param bool|false $ttl
* @return bool
*/
public function rm($name, $ttl = false)
{
$name = $_SERVER['HTTP_APPVERSION'] . '/' . $this->options['prefix'] . $name;
return false === $ttl ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return bool
*/
public function clear()
{
return $this->handler->flush();
}
/**
* 获得SaeKv对象
*/
private function getKv()
{
static $kv;
if (!$kv) {
$kv = new \SaeKV();
if (!$kv->init()) {
throw new Exception('KVDB init error');
}
}
return $kv;
}
}

View File

@@ -0,0 +1,763 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
/**
* Secache缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Secache
{
protected $handler = null;
protected $options = [
'project' => '',
'path' => '',
'expire' => 0,
'prefix' => '',
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = [])
{
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
if (substr($this->options['path'], -1) != '/') {
$this->options['path'] .= '/';
}
$this->handler = new SecacheClient;
$this->handler->workat($this->options['path'] . $this->options['project']);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$name = $this->options['prefix'] . $name;
$key = md5($name);
$this->handler->fetch($key, $return);
return $return;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return boolean
*/
public function set($name, $value)
{
$name = $this->options['prefix'] . $name;
$key = md5($name);
return $this->handler->store($key, $value);
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolen
*/
public function rm($name)
{
$name = $this->options['prefix'] . $name;
$key = md5($name);
return $this->handler->delete($key);
}
/**
* 清除缓存
* @access public
* @return boolen
*/
public function clear()
{
return $this->handler->_format(true);
}
}
if (!defined('SECACHE_SIZE')) {
define('SECACHE_SIZE', '15M');
}
class SecacheClient
{
public $idx_node_size = 40;
public $data_base_pos = 262588; //40+20+24*16+16*16*16*16*4;
public $schema_item_size = 24;
public $header_padding = 20; //保留空间 放置php标记防止下载
public $info_size = 20; //保留空间 4+16 maxsize|ver
//40起 添加20字节保留区域
public $idx_seq_pos = 40; //id 计数器节点地址
public $dfile_cur_pos = 44; //id 计数器节点地址
public $idx_free_pos = 48; //id 空闲链表入口地址
public $idx_base_pos = 444; //40+20+24*16
public $min_size = 10240; //10M最小值
public $schema_struct = array('size', 'free', 'lru_head', 'lru_tail', 'hits', 'miss');
public $ver = '$Rev: 3 $';
public $name = '系统默认缓存(文件型)';
public function workat($file)
{
$this->_file = $file . '.php';
$this->_bsize_list = array(
512 => 10,
3 << 10 => 10,
8 << 10 => 10,
20 << 10 => 4,
30 << 10 => 2,
50 << 10 => 2,
80 << 10 => 2,
96 << 10 => 2,
128 << 10 => 2,
224 << 10 => 2,
256 << 10 => 2,
512 << 10 => 1,
1024 << 10 => 1,
);
$this->_node_struct = array(
'next' => array(0, 'V'),
'prev' => array(4, 'V'),
'data' => array(8, 'V'),
'size' => array(12, 'V'),
'lru_right' => array(16, 'V'),
'lru_left' => array(20, 'V'),
'key' => array(24, 'H*'),
);
if (!file_exists($this->_file)) {
$this->create();
} else {
$this->_rs = fopen($this->_file, 'rb+') || $this->triggerError('Can\'t open the cachefile: ' . realpath($this->_file), E_USER_ERROR);
$this->_seek($this->header_padding);
$info = unpack('V1max_size/a*ver', fread($this->_rs, $this->info_size));
if ($info['ver'] != $this->ver) {
$this->_format(true);
} else {
$this->max_size = $info['max_size'];
}
}
$this->idx_node_base = $this->data_base_pos + $this->max_size;
$this->_block_size_list = array_keys($this->_bsize_list);
sort($this->_block_size_list);
return true;
}
public function create()
{
$this->_rs = fopen($this->_file, 'wb+') || $this->triggerError('Can\'t open the cachefile: ' . realpath($this->_file), E_USER_ERROR);
fseek($this->_rs, 0);
fputs($this->_rs, '<' . '?php exit()?' . '>');
return $this->_format();
}
public function _puts($offset, $data)
{
if ($offset < $this->max_size * 1.5) {
$this->_seek($offset);
return fputs($this->_rs, $data);
} else {
$this->triggerError('Offset over quota:' . $offset, E_USER_ERROR);
}
}
public function _seek($offset)
{
return fseek($this->_rs, $offset);
}
public function clear()
{
return $this->_format(true);
}
public function fetch($key, &$return)
{
$locked = false;
if ($this->lock(false)) {
$locked = true;
}
if ($this->search($key, $offset)) {
$info = $this->_get_node($offset);
$schema_id = $this->_get_size_schema_id($info['size']);
if (false === $schema_id) {
if ($locked) {
$this->unlock();
}
return false;
}
$this->_seek($info['data']);
$data = fread($this->_rs, $info['size']);
$return = unserialize($data);
if (false === $return) {
if ($locked) {
$this->unlock();
}
return false;
}
if ($locked) {
$this->_lru_push($schema_id, $info['offset']);
$this->_set_schema($schema_id, 'hits', $this->_get_schema($schema_id, 'hits') + 1);
return $this->unlock();
} else {
return true;
}
} else {
if ($locked) {
$this->unlock();
}
return false;
}
}
/**
* lock
* 如果flock不管用请继承本类并重载此方法
*
* @param mixed $is_block 是否阻塞
* @access public
* @return bool
*/
public function lock($is_block, $whatever = false)
{
return flock($this->_rs, $is_block ? LOCK_EX : LOCK_EX + LOCK_NB);
}
/**
* unlock
* 如果flock不管用请继承本类并重载此方法
*
* @access public
* @return bool
*/
public function unlock()
{
return flock($this->_rs, LOCK_UN);
}
public function delete($key, $pos = false)
{
if ($pos || $this->search($key, $pos)) {
if ($info = $this->_get_node($pos)) {
//删除data区域
if ($info['prev']) {
$this->_set_node($info['prev'], 'next', $info['next']);
$this->_set_node($info['next'], 'prev', $info['prev']);
} else {
//改入口位置
$this->_set_node($info['next'], 'prev', 0);
$this->_set_node_root($key, $info['next']);
}
$this->_free_dspace($info['size'], $info['data']);
$this->_lru_delete($info);
$this->_free_node($pos);
return $info['prev'];
}
}
return false;
}
public function store($key, $value)
{
if ($this->lock(true)) {
//save data
$data = serialize($value);
$size = strlen($data);
//get list_idx
$has_key = $this->search($key, $list_idx_offset);
$schema_id = $this->_get_size_schema_id($size);
if (false === $schema_id) {
$this->unlock();
return false;
}
if ($has_key) {
$hdseq = $list_idx_offset;
$info = $this->_get_node($hdseq);
if ($this->_get_size_schema_id($info['size']) == $schema_id) {
$dataoffset = $info['data'];
} else {
//破掉原有lru
$this->_lru_delete($info);
if (!($dataoffset = $this->_dalloc($schema_id))) {
$this->unlock();
return false;
}
$this->_free_dspace($info['size'], $info['data']);
$this->_set_node($hdseq, 'lru_left', 0);
$this->_set_node($hdseq, 'lru_right', 0);
}
$this->_set_node($hdseq, 'size', $size);
$this->_set_node($hdseq, 'data', $dataoffset);
} else {
if (!($dataoffset = $this->_dalloc($schema_id))) {
$this->unlock();
return false;
}
$hdseq = $this->_alloc_idx(array(
'next' => 0,
'prev' => $list_idx_offset,
'data' => $dataoffset,
'size' => $size,
'lru_right' => 0,
'lru_left' => 0,
'key' => $key,
));
if ($list_idx_offset > 0) {
$this->_set_node($list_idx_offset, 'next', $hdseq);
} else {
$this->_set_node_root($key, $hdseq);
}
}
if ($dataoffset > $this->max_size) {
$this->triggerError('alloc datasize:' . $dataoffset, E_USER_WARNING);
return false;
}
$this->_puts($dataoffset, $data);
$this->_set_schema($schema_id, 'miss', $this->_get_schema($schema_id, 'miss') + 1);
$this->_lru_push($schema_id, $hdseq);
$this->unlock();
return true;
} else {
$this->triggerError("Couldn't lock the file !", E_USER_WARNING);
return false;
}
}
/**
* search
* 查找指定的key
* 如果找到节点则$pos=节点本身 返回true
* 否则 $pos=树的末端 返回false
*
* @param mixed $key
* @access public
* @return mixed
*/
public function search($key, &$pos)
{
return $this->_get_pos_by_key($this->_get_node_root($key), $key, $pos);
}
public function _get_size_schema_id($size)
{
foreach ($this->_block_size_list as $k => $block_size) {
if ($size <= $block_size) {
return $k;
}
}
return false;
}
public function _parse_str_size($str_size, $default)
{
if (preg_match('/^([0-9]+)\s*([gmk]|)$/i', $str_size, $match)) {
switch (strtolower($match[2])) {
case 'g':
if ($match[1] > 1) {
$this->triggerError('Max cache size 1G', E_USER_ERROR);
}
$size = $match[1] << 30;
break;
case 'm':
$size = $match[1] << 20;
break;
case 'k':
$size = $match[1] << 10;
break;
default:
$size = $match[1];
}
if ($size <= 0) {
$this->triggerError('Error cache size ' . $this->max_size, E_USER_ERROR);
return false;
} elseif ($size < 10485760) {
return 10485760;
} else {
return $size;
}
} else {
return $default;
}
}
public function _format($truncate = false)
{
if ($this->lock(true, true)) {
if ($truncate) {
$this->_seek(0);
ftruncate($this->_rs, $this->idx_node_base);
}
$this->max_size = $this->_parse_str_size(SECACHE_SIZE, 15728640); //default:15m
$this->_puts($this->header_padding, pack('V1a*', $this->max_size, $this->ver));
ksort($this->_bsize_list);
$ds_offset = $this->data_base_pos;
$i = 0;
foreach ($this->_bsize_list as $size => $count) {
//将预分配的空间注册到free链表里
$count *= min(3, floor($this->max_size / 10485760));
$next_free_node = 0;
for ($j = 0; $j < $count; $j++) {
$this->_puts($ds_offset, pack('V', $next_free_node));
$next_free_node = $ds_offset;
$ds_offset += intval($size);
}
$code = pack(str_repeat('V1', count($this->schema_struct)), $size, $next_free_node, 0, 0, 0, 0);
$this->_puts(60 + $i * $this->schema_item_size, $code);
$i++;
}
$this->_set_dcur_pos($ds_offset);
$this->_puts($this->idx_base_pos, str_repeat("\0", 262144));
$this->_puts($this->idx_seq_pos, pack('V', 1));
$this->unlock();
return true;
} else {
$this->triggerError("Couldn't lock the file !", E_USER_ERROR);
return false;
}
}
public function _get_node_root($key)
{
$this->_seek(hexdec(substr($key, 0, 4)) * 4 + $this->idx_base_pos);
$a = fread($this->_rs, 4);
list(, $offset) = unpack('V', $a);
return $offset;
}
public function _set_node_root($key, $value)
{
return $this->_puts(hexdec(substr($key, 0, 4)) * 4 + $this->idx_base_pos, pack('V', $value));
}
public function _set_node($pos, $key, $value)
{
if (!$pos) {
return false;
}
if (isset($this->_node_struct[$key])) {
return $this->_puts($pos * $this->idx_node_size + $this->idx_node_base + $this->_node_struct[$key][0], pack($this->_node_struct[$key][1], $value));
} else {
return false;
}
}
public function _get_pos_by_key($offset, $key, &$pos)
{
if (!$offset) {
$pos = 0;
return false;
}
$info = $this->_get_node($offset);
if ($info['key'] == $key) {
$pos = $info['offset'];
return true;
} elseif ($info['next'] && $info['next'] != $offset) {
return $this->_get_pos_by_key($info['next'], $key, $pos);
} else {
$pos = $offset;
return false;
}
}
public function _lru_delete($info)
{
if ($info['lru_right']) {
$this->_set_node($info['lru_right'], 'lru_left', $info['lru_left']);
} else {
$this->_set_schema($this->_get_size_schema_id($info['size']), 'lru_tail', $info['lru_left']);
}
if ($info['lru_left']) {
$this->_set_node($info['lru_left'], 'lru_right', $info['lru_right']);
} else {
$this->_set_schema($this->_get_size_schema_id($info['size']), 'lru_head', $info['lru_right']);
}
return true;
}
public function _lru_push($schema_id, $offset)
{
$lru_head = $this->_get_schema($schema_id, 'lru_head');
$lru_tail = $this->_get_schema($schema_id, 'lru_tail');
if ((!$offset) || ($lru_head == $offset)) {
return;
}
$info = $this->_get_node($offset);
$this->_set_node($info['lru_right'], 'lru_left', $info['lru_left']);
$this->_set_node($info['lru_left'], 'lru_right', $info['lru_right']);
$this->_set_node($offset, 'lru_right', $lru_head);
$this->_set_node($offset, 'lru_left', 0);
$this->_set_node($lru_head, 'lru_left', $offset);
$this->_set_schema($schema_id, 'lru_head', $offset);
if (0 == $lru_tail) {
$this->_set_schema($schema_id, 'lru_tail', $offset);
} elseif ($lru_tail == $offset && $info['lru_left']) {
$this->_set_schema($schema_id, 'lru_tail', $info['lru_left']);
}
return true;
}
public function _get_node($offset)
{
$this->_seek($offset * $this->idx_node_size + $this->idx_node_base);
$info = unpack('V1next/V1prev/V1data/V1size/V1lru_right/V1lru_left/H*key', fread($this->_rs, $this->idx_node_size));
$info['offset'] = $offset;
return $info;
}
public function _lru_pop($schema_id)
{
if ($node = $this->_get_schema($schema_id, 'lru_tail')) {
$info = $this->_get_node($node);
if (!$info['data']) {
return false;
}
$this->delete($info['key'], $info['offset']);
if (!$this->_get_schema($schema_id, 'free')) {
$this->triggerError('pop lru,But nothing free...', E_USER_ERROR);
}
return $info;
} else {
return false;
}
}
public function _dalloc($schema_id, $lru_freed = false)
{
if ($free = $this->_get_schema($schema_id, 'free')) {
//如果lru里有链表
$this->_seek($free);
list(, $next) = unpack('V', fread($this->_rs, 4));
$this->_set_schema($schema_id, 'free', $next);
return $free;
} elseif ($lru_freed) {
$this->triggerError('Bat lru poped freesize', E_USER_ERROR);
return false;
} else {
$ds_offset = $this->_get_dcur_pos();
$size = $this->_get_schema($schema_id, 'size');
if ($size + $ds_offset > $this->max_size) {
if ($info = $this->_lru_pop($schema_id)) {
return $this->_dalloc($schema_id, $info);
} else {
$this->triggerError('Can\'t alloc dataspace', E_USER_ERROR);
return false;
}
} else {
$this->_set_dcur_pos($ds_offset + $size);
return $ds_offset;
}
}
}
public function _get_dcur_pos()
{
$this->_seek($this->dfile_cur_pos);
list(, $ds_offset) = unpack('V', fread($this->_rs, 4));
return $ds_offset;
}
public function _set_dcur_pos($pos)
{
return $this->_puts($this->dfile_cur_pos, pack('V', $pos));
}
public function _free_dspace($size, $pos)
{
if ($pos > $this->max_size) {
$this->triggerError('free dspace over quota:' . $pos, E_USER_ERROR);
return false;
}
$schema_id = $this->_get_size_schema_id($size);
if ($free = $this->_get_schema($schema_id, 'free')) {
$this->_puts($free, pack('V1', $pos));
} else {
$this->_set_schema($schema_id, 'free', $pos);
}
$this->_puts($pos, pack('V1', 0));
}
public function _dfollow($pos, &$c)
{
$c++;
$this->_seek($pos);
list(, $next) = unpack('V1', fread($this->_rs, 4));
if ($next) {
return $this->_dfollow($next, $c);
} else {
return $pos;
}
}
public function _free_node($pos)
{
$this->_seek($this->idx_free_pos);
list(, $prev_free_node) = unpack('V', fread($this->_rs, 4));
$this->_puts($pos * $this->idx_node_size + $this->idx_node_base, pack('V', $prev_free_node) . str_repeat("\0", $this->idx_node_size - 4));
return $this->_puts($this->idx_free_pos, pack('V', $pos));
}
public function _alloc_idx($data)
{
$this->_seek($this->idx_free_pos);
list(, $list_pos) = unpack('V', fread($this->_rs, 4));
if ($list_pos) {
$this->_seek($list_pos * $this->idx_node_size + $this->idx_node_base);
list(, $prev_free_node) = unpack('V', fread($this->_rs, 4));
$this->_puts($this->idx_free_pos, pack('V', $prev_free_node));
} else {
$this->_seek($this->idx_seq_pos);
list(, $list_pos) = unpack('V', fread($this->_rs, 4));
$this->_puts($this->idx_seq_pos, pack('V', $list_pos + 1));
}
return $this->_create_node($list_pos, $data);
}
public function _create_node($pos, $data)
{
$this->_puts($pos * $this->idx_node_size + $this->idx_node_base
, pack('V1V1V1V1V1V1H*', $data['next'], $data['prev'], $data['data'], $data['size'], $data['lru_right'], $data['lru_left'], $data['key']));
return $pos;
}
public function _set_schema($schema_id, $key, $value)
{
$info = array_flip($this->schema_struct);
return $this->_puts(60 + $schema_id * $this->schema_item_size + $info[$key] * 4, pack('V', $value));
}
public function _get_schema($id, $key)
{
$info = array_flip($this->schema_struct);
$this->_seek(60 + $id * $this->schema_item_size);
unpack('V1' . implode('/V1', $this->schema_struct), fread($this->_rs, $this->schema_item_size));
$this->_seek(60 + $id * $this->schema_item_size + $info[$key] * 4);
list(, $value) = unpack('V', fread($this->_rs, 4));
return $value;
}
public function _all_schemas()
{
$schema = [];
for ($i = 0; $i < 16; $i++) {
$this->_seek(60 + $i * $this->schema_item_size);
$info = unpack('V1' . implode('/V1', $this->schema_struct), fread($this->_rs, $this->schema_item_size));
if ($info['size']) {
$info['id'] = $i;
$schema[$i] = $info;
} else {
return $schema;
}
}
}
public function schemaStatus()
{
$return = [];
foreach ($this->_all_schemas() as $k => $schemaItem) {
if ($schemaItem['free']) {
$this->_dfollow($schemaItem['free'], $schemaItem['freecount']);
}
$return[] = $schemaItem;
}
return $return;
}
public function status(&$curBytes, &$totalBytes)
{
$totalBytes = $curBytes = 0;
$hits = $miss = 0;
$schemaStatus = $this->schemaStatus();
$totalBytes = $this->max_size;
$freeBytes = $this->max_size - $this->_get_dcur_pos();
foreach ($schemaStatus as $schema) {
$freeBytes += $schema['freecount'] * $schema['size'];
$miss += $schema['miss'];
$hits += $schema['hits'];
}
$curBytes = $totalBytes - $freeBytes;
$return[] = array('name' => '缓存命中', 'value' => $hits);
$return[] = array('name' => '缓存未命中', 'value' => $miss);
return $return;
}
public function triggerError($errstr, $errno)
{
triggerError($errstr, $errno);
}
}

View File

@@ -0,0 +1,124 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* Sqlite缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Sqlite implements CacheInterface
{
protected $options = [
'db' => ':memory:',
'table' => 'sharedmemory',
'prefix' => '',
'expire' => 0,
'persistent' => false,
];
/**
* 架构函数
* @param array $options 缓存参数
* @throws \BadFunctionCallException
* @access public
*/
public function __construct($options = [])
{
if (!extension_loaded('sqlite')) {
throw new \BadFunctionCallException('not support: sqlite');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open';
$this->handler = $func($this->options['db']);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$name = $this->options['prefix'] . sqlite_escape_string($name);
$sql = 'SELECT value FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\' AND (expire=0 OR expire >' . time() . ') LIMIT 1';
$result = sqlite_query($this->handler, $sql);
if (sqlite_num_rows($result)) {
$content = sqlite_fetch_single($result);
if (function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
return unserialize($content);
}
return false;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return boolean
*/
public function set($name, $value, $expire = null)
{
$name = $this->options['prefix'] . sqlite_escape_string($name);
$value = sqlite_escape_string(serialize($value));
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$expire = (0 == $expire) ? 0 : (time() + $expire); //缓存有效期为0表示永久缓存
if (function_exists('gzcompress')) {
//数据压缩
$value = gzcompress($value, 3);
}
$sql = 'REPLACE INTO ' . $this->options['table'] . ' (var, value,expire) VALUES (\'' . $name . '\', \'' . $value . '\', \'' . $expire . '\')';
if (sqlite_query($this->handler, $sql)) {
return true;
}
return false;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
$name = $this->options['prefix'] . sqlite_escape_string($name);
$sql = 'DELETE FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\'';
sqlite_query($this->handler, $sql);
return true;
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
$sql = 'DELETE FROM ' . $this->options['table'];
sqlite_query($this->handler, $sql);
return;
}
}

View File

@@ -0,0 +1,67 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
/**
* 测试缓存类
* @author liu21st <liu21st@gmail.com>
*/
class Test
{
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
return false;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
* @return boolean
*/
public function set($name, $value, $expire = null)
{
return true;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return true;
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return true;
}
}

View File

@@ -0,0 +1,96 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* Wincache缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Wincache
{
protected $options = [
'prefix' => '',
'expire' => 0,
];
/**
* 架构函数
* @param array $options 缓存参数
* @throws Exception
* @access public
*/
public function __construct($options = [])
{
if (!function_exists('wincache_ucache_info')) {
throw new \BadFunctionCallException('not support: WinCache');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$name = $this->options['prefix'] . $name;
return wincache_ucache_exists($name) ? wincache_ucache_get($name) : false;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return boolean
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
if (wincache_ucache_set($name, $value, $expire)) {
return true;
}
return false;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return wincache_ucache_delete($this->options['prefix'] . $name);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return;
}
}

View File

@@ -0,0 +1,99 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\cache\driver;
use think\Cache;
use think\Exception;
/**
* Xcache缓存驱动
* @author liu21st <liu21st@gmail.com>
*/
class Xcache
{
protected $options = [
'prefix' => '',
'expire' => 0,
];
/**
* 架构函数
* @param array $options 缓存参数
* @access public
* @throws \BadFunctionCallException
*/
public function __construct($options = [])
{
if (!function_exists('xcache_info')) {
throw new \BadFunctionCallException('not support: Xcache');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$name = $this->options['prefix'] . $name;
if (xcache_isset($name)) {
return xcache_get($name);
}
return false;
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
* @return boolean
*/
public function set($name, $value, $expire = null)
{
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
if (xcache_set($name, $value, $expire)) {
return true;
}
return false;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return xcache_unset($this->options['prefix'] . $name);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return;
}
}