我刚刚安装了Memcached,并且尝试使用它来缓存使用Doctrine ORM(Doctrine 2.4.8 +,Symfony 2.8+)完成的各种查询的结果。
我app/config/config_prod.yml
有这个:
doctrine:
orm:
metadata_cache_driver: memcached
result_cache_driver: memcached
query_cache_driver: memcached
我试图useResultCache()
在2个查询一样,(我只是置换对象的缓存ID这里的例子)return $query->useResultCache(true, 300, "my_cache_id")->getArrayResult();
。这里的特殊查询是因为它们的复杂性,它们是本机查询(SQL),但是该方法可用于任何查询(AbstractQuery类),因此我认为它应该可以工作。
不幸的是,事实并非如此。每次刷新页面时,如果我只是在数据库中进行了更改,就会显示更改。我检查了memcached的统计信息,似乎仍然有一些缓存命中,但是我真的不知道如何,比照。我刚才说的
有谁知道为什么这里似乎不使用缓存来获取所谓的缓存结果?我是否误解了某些内容,并且以某种方式忽略了TTL?
没有产生错误,memcached日志为空。
按照@nifr的要求,这是我创建2个本机查询的代码的布局,我在上面放置了Memcached测试:
$rsm = new ResultSetMapping;
$rsm->addEntityResult('my_entity_user', 'u');
// some $rsm->addFieldResult('u', 'column', 'field');
// some $rsm->addScalarResult('column', 'alias');
$sqlQuery = 'SELECT
...
FROM ...
INNER JOIN ... ON ...
INNER JOIN ... ON ...
// some more join
WHERE condition1
AND condition2';
// some conditions added depending on params passed to this function
$sqlQuery .= '
AND (fieldX = (subrequest1))
AND (fieldY = (subrequest2))
AND condition3
AND condition4
GROUP BY ...
ORDER BY ...
LIMIT :nbPerPage
OFFSET :offset
';
$query =
$this->_em->createNativeQuery($sqlQuery, $rsm)
// some ->setParameter('param', value)
;
return $query->useResultCache(true, 300, "my_cache_id")->getArrayResult();
因此,似乎由于某种原因,Doctrine无法成功获取ResultCacheDriver。我尝试在之前进行设置,useResultCache()
但是我遇到了Memcached的异常:Error: Call to a member function get() on null
。
我决定通过调用Memcached()更直接地做到这一点。我猜我将在控制器和存储库中执行此类操作,具体取决于我的需求。经过一些测试,它可以完美运行。
这基本上是我要做的:
$cacheHit = false;
$cacheId = md5("my_cache_id"); // Generate an hash for your cache id
// We check if Memcached exists, if it's not installed in dev environment for instance
if (class_exists('Memcached'))
{
$cache = new \Memcached();
$cache->addServer('localhost', 11211);
$cacheContent = $cache->get($cacheId);
// We check if the content is already cached
if ($cacheContent != false)
{
// Content cached, that's a cache hit
$content = $cacheContent;
$cacheHit = true;
}
}
// No cache hit ? We do our stuff and set the cache content for future requests
if ($cacheHit == false)
{
// Do the stuff you want to cache here and put it in a variable, $content for instance
if (class_exists('Memcached') and $cacheHit == false) $cache->set($cacheId, $content, time() + 600); // Here cache will expire in 600 seconds
}
我可能会把它放在服务中。尚不确定此类材料的“最佳实践”是什么。
编辑:我做了一项服务。但是它仅适用于本机sql ...因此问题仍然没有解决。
Edit²:我找到了一个有关此null问题的有效解决方案(这意味着找不到Memcached)。代码的位:
$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);
$doctrineMemcached = new \Doctrine\Common\Cache\MemcachedCache();
$doctrineMemcached->setMemcached($memcached);
$query
->setResultCacheDriver($doctrineMemcached)
->useResultCache(true, 300);
现在,我想知道应该config_prod.yml
使用哪个useResultCache()
功能才能使用该功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句