2017-04-19 142 views
4

我想使用新的Cache Component在Redis中存储数据。Symfony 3:使用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; 
} 

}

+0

你有这种方式使用它的任何错误?有什么不工作?你期望发生什么? – Chausser

+0

我没有错误,但我希望能够在2个“app.cache.codification”和“app.cache.another_pool”之间进行选择,每个池有不同的生命周期。我不知道该怎么做。 – melicerte

回答

0

为了揭露一个游泳池作为一种服务,你需要两个额外的选项: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 

Now yo ü可以通过引用其名称中使用两个池的服务:

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

干杯!