sitegeist/stalemate

具有过期期限和异步更新的缓存

v1.0.1 2022-10-14 09:48 UTC

This package is auto-updated.

Last update: 2024-09-09 13:29:34 UTC


README

Neos.Flow的类似Varnish的缓存,具有异步更新,并在同时返回过期结果

此包实现了一个缓存,在缓存值异步更新的同时,将返回可配置时间内的过期值。这种行为在varnish缓存中很常见,但在PHP中并不常见。

核心概念是,当无法在缓存中找到所需信息时,staleMateCache会获取一个identifier和一个用于生成所需信息的closure。如果未找到缓存的 结果,则立即调用closure。如果找到结果,则返回缓存的 结果。

如果缓存的项已超过预期寿命,则仍会立即返回过期项,但closure将在流应用程序关闭时调度进行评估,因此响应已发送给用户。

作者 & 赞助商

本包的开发和公开发布得到了我们的雇主https://www.sitegeist.de的大力赞助。

用法

StaleMate缓存从flow中注入。

    use \Sitegeist\StaleMate\Cache\ClosureCache as StaleMateCache;     
    
    /**
     * @var VariableFrontend
     */
    protected $cache;
    
    /**
     * @var StaleMateCache
     */
    protected $staleMateCache;

    /**
     * @param VariableFrontend $cache
     * @return void
     */
    public function injectCache(VariableFrontend $cache): void
    {
        $this->cache = $cache;
    }
    
    public function initializeObject()
    {
        $staleMateCache = new \Sitegeist\StaleMate\Cache\ClosureCache(
            $this->cache, // the variable frontend to cache the data in
            8600, // lifetime for the items
            4300, // gracePeriod where items are updated asynchronous
            60 // lockPeriod for asynchronous updates 
        );
    }

然后通过resolve方法使用identifierclosure来调用缓存。请注意,closure不能有参数,而是可以use从方法调用的上下文中获取的变量。

    $result = $this->staleMateCache->resolve(
        $cacheId, // identifier used to store the result, has to be unique
        function () use ($stuffThatIsNeeded) {
            $response = ... some expensive operation ...
            return $response;
        }, // closure to generate the result if no result is in the cache
        ['someTag'], // tags for the cache item  
        86400, // lifetime of the cached result until a refresh is needed
        43200, // gracePeriod after lifetime where an update is performed async and the stale result is used
        60 // lockPeriod for asynchronous updates 
    );

安装

Sitegeist.StaleMate通过packagist提供。只需运行composer require sitegeist/stalemate即可安装。我们使用语义版本控制,因此每次重大更改都会增加主版本号。

与Symfony Cache Contracts的比较

此处实现的方法与symfony缓存契约有些类似,但在某些方面有所不同。symfony缓存契约会在缓存条目过期前掷骰子以升级缓存条目,以防止大规模无效化和重新计算。另一方面,stalemate将返回缓存项并在响应发送给用户后重新计算值。

贡献

我们非常乐意接受贡献。请向我们发送拉取请求。