2017-04-19 61 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

乾杯!