Symfony 3:使用Redis配置缓存组件池

时间:2017-04-19 15:36:35

标签: symfony redis symfony-3.2

我想使用新的Cache Component在Redis中存储数据。

我想配置具有不同数据生命周期的池。

现在,我配置了:

framework:
    cache:
        app: cache.adapter.redis
        default_redis_provider: "redis://localhost:6379"
        pools:
            app.cache.codification:
                adapter: cache.app
                default_lifetime: 86400
            app.cache.another_pool:
                adapter: cache.app
                default_lifetime: 600

但我不知道如何在我的代码中使用app.cache.codification池。 我宣布了以下服务:

acme.cache.repository.code_list:
    class: Acme\Cache\Repository\CodeList
    public: false
    arguments:
        - "@cache.app"
        - "@acme.webservice.repository.code_list"

我这样使用它:

class CodeList
{
    private $webserviceCodeList;

    /**
     * @var AbstractAdapter
     */
    private $cacheAdapter;

    public static $CACHE_KEY = 'webservices.codification.search';

    private $lists;

    /**
     * @param AbstractAdapter $cacheAdapter
     * @param WebserviceCodeList $webserviceCodeList
     */
    public function __construct($cacheAdapter, $webserviceCodeList)
    {
        $this->cacheAdapter = $cacheAdapter;
        $this->webserviceCodeList = $webserviceCodeList;
    }

    /**
     * @param string $listName
     * @return array
     */
    public function getCodeList(string $listName)
    {
        if ($this->lists !== null) {
            return $this->lists;
        }

        // Cache get item
        $cacheItem = $this->cacheAdapter->getItem(self::$CACHE_KEY);

        // Cache HIT
        if ($cacheItem->isHit()) {
            $this->lists = $cacheItem->get();
            return $this->lists;
        }

        // Cache MISS
        $this->lists = $this->webserviceCodeList->getCodeList($listName);
        $cacheItem->set($this->lists);
        $this->cacheAdapter->save($cacheItem);

        return $this->lists;
    }
}

1 个答案:

答案 0 :(得分:2)

要将池公开为服务,您需要两个额外选项:namepublic,如下所示:

framework:
    cache:
        app: cache.adapter.redis
        default_redis_provider: "redis://localhost:6379"
        pools:
            app.cache.codification:
                name: app.cache.codification # this will be the service's name
                public: true # this will expose the pool as a service
                adapter: cache.app
                default_lifetime: 86400
            app.cache.another_pool:
                name: app.cache.another_pool
                public: true
                adapter: cache.app
                default_lifetime: 600

现在,您可以通过引用其名称来将两个池用作服务:

acme.cache.repository.code_list:
    class: Acme\Cache\Repository\CodeList
    public: false
    arguments:
        - "@app.cache.codification" # pool's name
        - "@acme.webservice.repository.code_list"

有关缓存选项的更多详细信息:http://symfony.com/doc/current/reference/configuration/framework.html#public

干杯!