corneltek/universal-cache

一种通用的PHP缓存接口,具有级联缓存功能

3.3.0 2016-06-11 07:29 UTC

This package is auto-updated.

Last update: 2024-08-29 03:47:34 UTC


README

Build Status Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads License

一种通用的PHP缓存接口,具有级联缓存功能。

描述

本包受Perl模块Cache::Cascade的启发。

在多进程,尤其是多服务器应用程序中,缓存是一种非常有效的提高性能的手段。

增加缓存规模带来的权衡是增加了复杂性。例如,在基于FastMmap的存储中进行缓存比使用基于内存的缓存要慢得多,因为必须锁定页面以确保不会发生损坏。同样,Memcached比FastMmap的额外开销更大,因为它受网络限制,并且在客户端使用阻塞IO。

本模块尝试使用多个后端实现缓存的透明级联。

思路是从最便宜的缓存后端开始搜索,到最昂贵的,并且根据选项在更便宜的缓存后端中缓存结果。

使用级联的好处是,如果在一个慢速缓存中命中的机会非常高,但与检查便宜缓存相比几乎可以忽略不计,我们可能已经在便宜缓存中得到了我们想要的结果。配置你的过期策略,使得缓存命中概率(更大的缓存)在级联的每一层大约提高一个数量级。

安装

composer require corneltek/universal-cache

UniversalCache

UniversalCache类提供了对不同的缓存后端操作的一致接口,你可以将最快的缓存后端放在第一位,这样当在最快的存储中存在新鲜缓存时,你可以非常快地获取缓存。

use UniversalCache\ApcuCache;
use UniversalCache\FileSystemCache;
use UniversalCache\UniversalCache;

$cache = new UniversalCache([
    new ArrayCache, // Fetch cache without serialization if there is a request-wide cache exists.
    new ApcuCache('app_', 60), // Faster then file system cache.
    new FileSystemCache(__DIR__ . '/cache'),
]);
$cache->set('key', 'value');
$value = $cache->get('key');

ApcuCache

$cache = new UniversalCache\ApcuCache('app_', 3600); // 3600 = expiry time
$cache->set($name,$val);
$val = $cache->get($name);
$cache->remove($name);

ArrayCache

ArrayCache实现了一个基于纯PHP的缓存,缓存不会在不同的请求之间持久化。然而,它使请求范围内的缓存变得简单。

$cache = new UniversalCache\ArrayCache;
$cache->set($name,$val);
$val = $cache->get($name);
$cache->remove($name);

MemcacheCache

$cache = new UniversalCache\MemcacheCache([
    'servers' => [['localhost', 123123], ['server2',123123] ]
]);
$cache->set($name,$val);
$val = $cache->get($name);
$cache->remove($name);

RedisCache

$cache = new UniversalCache\RedisCache($redisConnection);
$cache->set($name,$val);
$val = $cache->get($name);
$cache->remove($name);

FileSystemCache

$serializer = new SerializerKit\JsonSerializer();
$cache = new UniversalCache\FileSystemCache(__DIR__ . '/cache', [
    'expiry' => 30,
    'serializer' => $serializer,
]);

开发

安装依赖项

composer install --prefer-source

安装redis扩展

phpbrew ext install github:phpredis/phpredis php7

安装memcached扩展

phpbrew ext install github:php-memcached-dev/php-memcached php7 -- --disable-memcached-sasl

安装APCu扩展

phpbrew ext install github:krakjoe/apcu

请确保启用apcu和cli模式

apc.enabled=1
apc.enable_cli=1

运行测试

phpunit

授权

本包在MIT授权下发布。