becklyn/cache

提供简单(且快速)缓存的缓存包

安装次数: 8,717

依赖者: 1

建议者: 0

安全性: 0

星标: 1

关注者: 5

分支: 0

开放问题: 0

类型:symfony-bundle

1.1.0 2022-02-17 14:22 UTC

This package is auto-updated.

Last update: 2024-09-17 20:07:39 UTC


README

提供简单缓存,易于使用且性能高。警告:对于高度并发的使用,您应提前准备缓存或使用symfony自带的缓存,因为它具有适当的缓存雪崩保护。

使用方法

获取简单缓存工厂并获取缓存项

use Becklyn\Cache\Cache\SimpleCacheFactory;

class MyService
{
    private SimpleCacheItemInterface $cache;

    /**
     */
    public function __construct (SimpleCacheFactory $cacheFactory)
    {
        $this->cache = $cacheFactory->getItem(
            "my.cache.key",
            fn () => $this->loadItems()
        );
    }


    /**
     * Returns the cached or fresh items, depending on several conditions. 
     */
    public function getItems () : array
    {
        return $this->cache->get();
    }
    

    /**
     * Loads the items from the database
     */
    public function loadItems () : array
    {
        // ...
    }
}

基于Symfony配置的缓存

您可以将缓存键和生成器传递给 getItem() 方法(如上面的示例所示),或者您可以额外传递需要跟踪和用于缓存失效的资源。

如果您传递资源,这将是一个两级缓存

  1. 第一级将是普通的 symfony/cache,它非常快,但没有适当的缓存失效方式。
  2. 第二级将是 ConfigCache,如果跟踪的资源中的一些发生变化,它将自动失效。
$cacheFactory->getItem(
    "my.cache.key",
    fn () => $this->loadItems(),
    // eg. if your cache status depends on routing resources
    $this->router->getRouteCollection()->getResources()
 );