热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

php缓存类实现支持apc和文件缓存

 发现一个PHP缓存实现,实现了apc和文件缓存,继承Cache_Abstract即可实现调用第三方的缓存工具。参考shindig的缓存类和apc。代码如下:<?phpclassCacheExceptionextendsException{}***缓存抽象类*abstractclassCach
发现一个PHP缓存实现,实现了apc和文件缓存,继承Cache_Abstract即可实现调用第三方的缓存工具。参考shindig的缓存类和apc。

代码如下:

 isLocked($key)) {
			return $this;
		}

		$tries = 10;
		$count = 0;
		do {
			usleep(200);
			$count++;
		} while ($count <= $tries && $this->isLocked($key));// 最多做十次睡眠等待解锁,超时则跳过并解锁

		$this -> isLocked($key) && $this -> unlock($key);

		return $this;
	}

}

/**
 * APC扩展缓存实现
 *
 *
 * @category   Mjie
 * @package    Cache
 * @author     流水孟春
 * @copyright  Copyright (c) 2008- 
 * @license    New BSD License
 * @version    $Id: Cache/Apc.php 版本号 2010-04-18 23:02 cmpan $
 */
class Cache_Apc extends Cache_Abstract {

	protected $_prefix = 'cache.mjie.net';

	public function __construct() {
		if (!function_exists('apc_cache_info')) {
			throw new CacheException('apc extension didn\'t installed');
		}
	}

	/**
	 * 保存缓存变量
	 *
	 * @param string $key
	 * @param mixed $value
	 * @return bool
	 */
	public function store($key, $value) {
		return apc_store($this -> _storageKey($key), $value);
	}

	/**
	 * 读取缓存
	 *
	 * @param string $key
	 * @return mixed
	 */
	public function fetch($key) {
		return apc_fetch($this -> _storageKey($key));
	}

	/**
	 * 清除缓存
	 *
	 * @return Cache_Apc
	 */
	public function clear() {
		apc_clear_cache();
		return $this;
	}

	/**
	 * 删除缓存单元
	 *
	 * @return Cache_Apc
	 */
	public function delete($key) {
		apc_delete($this -> _storageKey($key));
		return $this;
	}

	/**
	 * 缓存单元是否被锁定
	 *
	 * @param string $key
	 * @return bool
	 */
	public function isLocked($key) {
		if ((apc_fetch($this -> _storageKey($key) . '.lock')) === false) {
			return false;
		}

		return true;
	}

	/**
	 * 锁定缓存单元
	 *
	 * @param string $key
	 * @return Cache_Apc
	 */
	public function lock($key) {
		apc_store($this -> _storageKey($key) . '.lock', '', 5);
		return $this;
	}

	/**
	 * 缓存单元解锁
	 *
	 * @param string $key
	 * @return Cache_Apc
	 */
	public function unlock($key) {
		apc_delete($this -> _storageKey($key) . '.lock');
		return $this;
	}

	/**
	 * 完整缓存名
	 *
	 * @param string $key
	 * @return string
	 */
	private function _storageKey($key) {
		return $this -> _prefix . '_' . $key;
	}

}

/**
 * 文件缓存实现
 *
 *
 * @category   Mjie
 * @package    Cache
 * @author     流水孟春
 * @copyright  Copyright (c) 2008- 
 * @license    New BSD License
 * @version    $Id: Cache/File.php 版本号 2010-04-18 16:46 cmpan $
 */
class Cache_File extends Cache_Abstract {
	public $useSubdir = false;

	protected $_cachesDir = 'cache';

	public function __construct() {
		if (defined('DATA_DIR')) {
			$this -> _setCacheDir(DATA_DIR . '/cache');
		}
	}

	/**
	 * 获取缓存文件
	 *
	 * @param string $key
	 * @return string
	 */
	protected function _getCacheFile($key) {
		$subdir = $this -> useSubdir ? substr($key, 0, 2) . '/' : '';
		return $this -> _cachesDir . '/' . $subdir . $key . '.php';
	}

	/**
	 * 读取缓存变量
	 * 为防止信息泄露,缓存文件格式为php文件,并以""开头
	 *
	 * @param string $key 缓存下标
	 * @return mixed
	 */
	public function fetch($key) {
		$cacheFile = self::_getCacheFile($key);
		if (file_exists($cacheFile) && is_readable($cacheFile)) {
			// include 方式
			//return include $cacheFile;
			// 系列化方式

			return unserialize(@file_get_contents($cacheFile, false, NULL, 13));
		}

		return false;
	}

	/**
	 * 缓存变量
	 * 为防止信息泄露,缓存文件格式为php文件,并以""开头
	 *
	 * @param string $key 缓存变量下标
	 * @param string $value 缓存变量的值
	 * @return bool
	 */
	public function store($key, $value) {
		$cacheFile = self::_getCacheFile($key);
		$cacheDir = dirname($cacheFile);

		if (!is_dir($cacheDir)) {
			if (!@mkdir($cacheDir, 0755, true)) {
				throw new CacheException("Could not make cache directory");
			}
		}
		// 用include方式
		//return @file_put_contents($cacheFile, '' . serialize($value));
	}

	/**
	 * 删除缓存变量
	 *
	 * @param string $key 缓存下标
	 * @return Cache_File
	 */
	public function delete($key) {
		if (emptyempty($key)) {
			throw new CacheException("Missing argument 1 for Cache_File::delete()");
		}

		$cacheFile = self::_getCacheFile($key);
		if (!@unlink($cacheFile)) {
			throw new CacheException("Cache file could not be deleted");
		}

		return $this;
	}

	/**
	 * 缓存单元是否已经锁定
	 *
	 * @param string $key
	 * @return bool
	 */
	public function isLocked($key) {
		$cacheFile = self::_getCacheFile($key);
		clearstatcache();
		return file_exists($cacheFile . '.lock');
	}

	/**
	 * 锁定
	 *
	 * @param string $key
	 * @return Cache_File
	 */
	public function lock($key) {
		$cacheFile = self::_getCacheFile($key);
		$cacheDir = dirname($cacheFile);
		if (!is_dir($cacheDir)) {
			if (!@mkdir($cacheDir, 0755, true)) {
				if (!is_dir($cacheDir)) {
					throw new CacheException("Could not make cache directory");
				}
			}
		}

		// 设定缓存锁文件的访问和修改时间
		@touch($cacheFile . '.lock');
		return $this;
	}

	/**
	 * 解锁
	 *
	 * @param string $key
	 * @return Cache_File
	 */
	public function unlock($key) {
		$cacheFile = self::_getCacheFile($key);
		@unlink($cacheFile . '.lock');
		return $this;
	}

	/**
	 * 设置文件缓存目录
	 * @param string $dir
	 * @return Cache_File
	 */
	protected function _setCacheDir($dir) {
		$this -> _cachesDir = rtrim(str_replace('\\', '/', trim($dir)), '/');
		clearstatcache();
		if (!is_dir($this -> _cachesDir)) {
			mkdir($this -> _cachesDir, 0755, true);
		}
		//
		return $this;
	}

	/**
	 * 清空所有缓存
	 *
	 * @return Cache_File
	 */
	public function clear() {
		// 遍历目录清除缓存
		$cacheDir = $this -> _cachesDir;
		$d = dir($cacheDir);
		while (false !== ($entry = $d -> read())) {
			if ('.' == $entry[0]) {
				continue;
			}

			$cacheEntry = $cacheDir . '/' . $entry;
			if (is_file($cacheEntry)) {
				@unlink($cacheEntry);
			} elseif (is_dir($cacheEntry)) {
				// 缓存文件夹有两级
				$d2 = dir($cacheEntry);
				while (false !== ($entry = $d2 -> read())) {
					if ('.' == $entry[0]) {
						continue;
					}

					$cacheEntry .= '/' . $entry;
					if (is_file($cacheEntry)) {
						@unlink($cacheEntry);
					}
				}
				$d2 -> close();
			}
		}
		$d -> close();

		return $this;
	}

}

/**
 * 缓存单元的数据结构
 * array(
 *         'time' => time(),     // 缓存写入时的时间戳
 *         'expire' => $expire, // 缓存过期时间
 *         'valid' => true,         // 缓存是否有效
 *         'data' => $value         // 缓存的值
 * );
 */
final class Cache {
	/**
	 * 缓存过期时间长度(s)
	 *
	 * @var int
	 */
	private $_expire = 3600;
	/**
	 * 缓存处理类
	 *
	 * @var Cache_Abstract
	 */
	private $_storage = null;
	/**
	 * @return Cache
	 */
	static public function createCache($cacheClass = 'Cache_File') {
		return new self($cacheClass);
	}

	private function __construct($cacheClass) {
		$this -> _storage = new $cacheClass();
	}

	/**
	 * 设置缓存
	 *
	 * @param string $key
	 * @param mixed $value
	 * @param int $expire
	 */
	public function set($key, $value, $expire = false) {
		if (!$expire) {
			$expire = $this -> _expire;
		}

		$this -> _storage -> checkLock($key);

		$data = array('time' => time(), 'expire' => $expire, 'valid' => true, 'data' => $value);
		$this -> _storage -> lock($key);

		try {
			$this -> _storage -> store($key, $data);
			$this -> _storage -> unlock($key);
		} catch (CacheException $e) {
			$this -> _storage -> unlock($key);
			throw $e;
		}
	}

	/**
	 * 读取缓存
	 *
	 * @param string $key
	 * @return mixed
	 */
	public function get($key) {
		$data = $this -> fetch($key);
		if ($data && $data['valid'] && !$data['isExpired']) {
			return $data['data'];
		}

		return false;
	}

	/**
	 * 读缓存,包括过期的和无效的,取得完整的存贮结构
	 *
	 * @param string $key
	 */
	public function fetch($key) {
		$this -> _storage -> checkLock($key);
		$data = $this -> _storage -> fetch($key);
		if ($data) {
			$data['isExpired'] = (time() - $data['time']) > $data['expire'] ? true : false;
			return $data;
		}

		return false;
	}

	/**
	 * 删除缓存
	 *
	 * @param string $key
	 */
	public function delete($key) {
		$this -> _storage -> checkLock($key) -> lock($key) -> delete($key) -> unlock($key);
	}

	public function clear() {
		$this -> _storage -> clear();
	}

	/**
	 * 把缓存设为无效
	 *
	 * @param string $key
	 */
	public function setInvalidate($key) {
		$this -> _storage -> checkLock($key) -> lock($key);
		try {
			$data = $this -> _storage -> fetch($key);
			if ($data) {
				$data['valid'] = false;
				$this -> _storage -> store($key, $data);
			}
			$this -> _storage -> unlock($key);
		} catch (CacheException $e) {
			$this -> _storage -> unlock($key);
			throw $e;
		}
	}

	/**
	 * 设置缓存过期时间(s)
	 *
	 * @param int $expire
	 */
	public function setExpire($expire) {
		$this -> _expire = (int)$expire;
		return $this;
	}

}


推荐阅读
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • Echarts图表重复加载、axis重复多次请求问题解决记录
    文章目录1.需求描述2.问题描述正常状态:问题状态:3.解决方法1.需求描述使用Echats实现了一个中国地图:通过选择查询周期&#x ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • Python字典推导式及循环列表生成字典方法
    本文介绍了Python中使用字典推导式和循环列表生成字典的方法,包括通过循环列表生成相应的字典,并给出了执行结果。详细讲解了代码实现过程。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • “你永远都不知道明天和‘公司的意外’哪个先来。”疫情期间,这是我们最战战兢兢的心情。但是显然,有些人体会不了。这份行业数据,让笔者“柠檬” ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • 生成对抗式网络GAN及其衍生CGAN、DCGAN、WGAN、LSGAN、BEGAN介绍
    一、GAN原理介绍学习GAN的第一篇论文当然由是IanGoodfellow于2014年发表的GenerativeAdversarialNetworks(论文下载链接arxiv:[h ... [详细]
author-avatar
乃君敏睿64
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有