symfony使用緩存

2019-07-19 18:31:00
CJL
原創
3496

蔘考文檔:

https://symfony.com/doc/4.2/components/cache.html The Cache Component



使用默認文件緩存

1、註入CacheInterface $cache

public function __construct(CacheInterface $cache)
{
    $this->cache = $cache;
}

2、使用方法一

$idsCache = $this->cache->getItem('cache_virtual_user_ids');
if (!$idsCache->isHit()) {
    $ids = $this->getAllUserId($type); //穫取原始數據
    $idsCache->set($ids);
    $idsCache->expiresAfter(3600);
    $this->cache->save($idsCache);
} else {
    $ids = $idsCache->get();
}

3、使用方法二(推薦)

$ids = $this->cache->get('cache_virtual_user_ids', function (CacheItem $cacheItem) use ($type) {
    $cacheItem->expiresAfter(3600);
    return $this->getAllUserId($type); //穫取原始數據
});


使用redis做緩存

1、配置

.env配置連接DSN

REDIS_URL_DSN=redis://9f83d4682ba8b962@10.0.0.221:6379

config/packages/cache.yaml 配置緩存池

framework:
    cache:
        default_redis_provider: '%env(resolve:REDIS_URL_DSN)%'
        pools:
            user.cache:
                adapter: cache.adapter.redis

2、註入(變量名需與pool的命名一緻轉爲駝峰命名,如user.cache爲$userCache)建議去除存儲類型標識,方便後期切換緩存存儲引擎切換

public function __construct(CacheInterface $userCache)
{
    $this->cache = $userCache;
}

3、使用與文件緩存使用的方式一緻



清除緩存

php bin/console cache:clear

php bin/console cache:pool:clear cache.global_clearer

詳細蔘考:https://symfony.com/doc/4.2/cache.html#clearing-the-cache


緩存使用效果查看

安裝Profiler可以查詢數據庫的查詢及cache的命中

https://symfony.com/doc/4.2/profiler.html



發錶評論
評論通過審核後顯示。
流量統計