whales/cache

此包最新版本(0.2.0)没有可用的许可证信息。

缓存库

0.2.0 2014-11-01 19:02 UTC

This package is not auto-updated.

Last update: 2024-09-24 01:49:17 UTC


README

#Cache ##示例 ###Stampede Protection ####对象实例化

	// Service in need of caching and stampede protection
	$callableService = function ($key) { return 'resourceIntensiveData'; };

	// Would need to be database-backed lock to actual work in the example
	// since the InMemoryLock has a per request lifecycle.
	$lock = new Cache\StampedeProtection\Locks\InMemoryLock;

	$memcached = new \Memcached();
	$memcached->addServer('127.0.0.1', 11211);

	$transientCache = new Cache\Maps\MemcachedCacheMap($memcached);

	// Acts as stale cache while service is processing data
	$persistentCache = new Cache\Maps\PdoCacheMap(
		new \PDO('mysql:host=localhost;dbname=test'),
		'cache'
	);

####对象组合

	$cachedService = new CallableServiceCachingDecorator(
		new MutexLockAcquiringDecorator(
			$callableService,
			$lock,
			$persistentCache
		),
		new LockReleaseOnSettingCacheMap(
			new LinkedNodeCacheMap(
				$transientCache,
				new LockAffectedCacheMap(
					$persistentCache,
					$lock
				)
			),
			$lock
		)
	);

	$data = call_user_func($cachedService, 'key1234');

####说明

假设:$persistentCache 已初始化,以确保在检索/重新生成新数据的同时,始终返回一些数据。

  • 当请求进入 $cachedService 时,它将尝试在缓存中查找项目
    • 调用 find 的方法将通过
      • LockReleaseOnSettingCacheMap 传递,它委托给
      • LinkedNodeCacheMap
        • 在这里,它将首先检查 $transientCache,并在以下情况下返回缓存值,即
          • 命中,在这种情况下,它将返回缓存值并一直返回到原始调用者。
          • 未命中然后
            • 检查 $persistentCache,它是预先初始化的,应该导致命中,但是由于 LockAffectedCacheMap 包装了 $persistentCache,它将报告缓存未命中,因为锁可用(即,没有人目前正在从原始数据源检索并重新生成缓存数据)
            • 缓存未命中将一直传播到 CallableServiceCachingDecorator。
    • 由于 find 返回的迭代器为空,因此代码需要调用实际的服务以检索新鲜数据。
      • 对服务的调用将通过 MutexLockAcquiringDecorator 对象传递,该对象将获取锁并让所有未来的服务请求知道有人目前正在从原始数据源检索数据并重新生成新的缓存数据。
      • 在持有锁的同时,所有未来的请求都将从过时的 $persistentCache 中检索数据。记住,由于这被包装在 LockAffectedCacheMap 中,并且锁现在不可用,因此 $persistentCache 将报告缓存命中并返回其过时的数据。
    • 在调用服务并返回新鲜数据到 CallableServiceCachingDecorator 后,我们设置缓存以反映新数据。
    • 对 set 的调用将通过 LockReleaseOnSettingCacheMap 传递,它将委托设置到 LinkedNodeCacheMap,然后它将把新数据添加到 $transientCache 和 $persistentCache(未来的过时缓存)中。
    • 设置新值后,则释放锁。
    • 最后,将新鲜数据传递给顶级调用者。