jnilla / joomla-cache-helper
使用Joomla缓存支持,快速且简单
README
一个简化Joomla缓存使用的辅助工具。
这个辅助工具基于原生Joomla缓存支持构建。我们实现了一个更简单的API,并添加了一些额外功能,使辅助工具更实用。
安装
使用Composer安装
$ composer require jnilla/joomla-cache-helper
使用Composer自动加载器加载库
require('vendor/autoload.php');
基本用法
声明
use Jnilla\Joomla\CacheHelper as CacheHelper;
存储数据到缓存
CacheHelper::set('idHere', 'groupNameHere', 'Some string data here');
从缓存获取数据
$cache = CacheHelper::get('idHere', 'groupNameHere');
// $cache var dump
array (size=4)
'isValid' => boolean true
'isUpdating' => boolean false
'isTimeout' => boolean false
'data' => string 'Some string data here' (length=0)
代理方法
$cache = CacheHelper::proxy(
'idHere', // Cache Id
'groupNameHere', // Cache Group
function(){return 'Some string data here';}, // Callback that returns the data to cache
6, // Cache Lifetime
15 // Wait if updating
);
// $cache var dump
array (size=4)
'isValid' => boolean true
'isUpdating' => boolean false
'isTimeout' => boolean false
'data' => string 'Some string data here' (length=0)
如果标志 isValid
为 true
,则可以安全地使用缓存项数据。
使用此库的最实用的方法是使用 proxy
方法。
此方法充当2合1的中介,在需要时自动获取和更新缓存项。
工作原理
- 如果缓存项不是过时的,则方法返回缓存项。
- 如果缓存项是过时的,则方法执行回调,将结果存储在缓存中,并返回更新后的缓存项。
远程数据的示例
$cache = CacheHelper::callback(
'idHere', // Cache Id
'groupNameHere', // Cache Group
function(){return file_get_contents('https://jsonplaceholder.typicode.com/todos');}, // Callback that returns the data to cache
6, // Cache Lifetime
15 // Wait if updating
);
// $cache var dump
array (size=4)
'isValid' => boolean true
'isUpdating' => boolean false
'isTimeout' => boolean false
'data' => string '{some JSON code from that source}' (length=0)
生命周期是在缓存项被认为是过时并需要更新之前的时间。
需要注意的是,我们可以使用 $lifetime
参数作为请求速率限制机制,例如使用以下公式:60秒 / 请求次数 = 生命周期。例如:对于每分钟10个请求的速率限制,使用:60秒 / 10请求 = 10秒。
等待机制
存在一个等待机制,这在某些使用情况下很有用。
方法 get
和 proxy
共享以下参数
- @param integer $wait: 如果缓存项正在更新,则强制当前操作等待的时间(秒)。
情况1
5个用户首次同时使用 proxy
方法请求远程数据,且 $wait
不是 0
。
首先使用 proxy
方法的用户触发 isUpdading
标志,所有人都要等待远程获取操作完成。之后,所有人同时获得相同的数据。
情况2
5个用户首次同时使用 proxy
方法请求远程数据,且 $wait
是 0
。
首先使用 proxy
方法的用户触发 isUpdading
标志,只有这位用户可以等待远程获取操作完成。其他人同时收到一个空的缓存项。
这种情况在第一次请求远程数据时很有用,如果不想让所有人都锁定在等待期间。
这种行为有助于减轻服务器RAM的使用,因为请求/CPU线程的存活时间更短。
情况3
5个用户首次同时使用 proxy
方法请求远程数据,且 $wait
不是 0
,但远程操作耗时过长。
首先使用 proxy
方法的用户触发 isUpdading
标志,所有人都要等待。如果达到 $wait
时间,则将 isUpdading
标志设置为 false
,将 isTimeout
标志设置为 true
,所有人同时收到一个空的缓存项。
这防止了过长或无限等待时间。
许可
本项目遵循MIT许可证。