【问题标题】:Cache SELECT query using Doctrine Entity Manager使用 Doctrine Entity Manager 缓存 SELECT 查询
【发布时间】:2014-09-30 20:35:21
【问题描述】:

我在代码中多次使用 Doctrine Entity Manager,例如:

$em = $this->getDoctrine()->getManager();
$countries = $em->getRepository('CommonBundle:Country')->findAll();

可以以这种格式使用 Doctrine Cache 吗?我看到了很多文档,但它们都与 Doctrine Query Builder 相关,有什么建议吗?如何为SELECT查询启用缓存?

缓存不起作用(很难)

我正在处理缓存结果,我这样做是为了缓存一些查询:

  • config.ymlorm 配置下启用 APC:

    doctrine:
        dbal:
            driver:   "%database_driver%"
            host:     "%database_host%"
            port:     "%database_port%"
            dbname:   "%database_name%"
            user:     "%database_user%"
            password: "%database_password%"
            charset:  UTF8
        orm:
            auto_generate_proxy_classes: "%kernel.debug%"
            auto_mapping: true
            metadata_cache_driver: apc
            result_cache_driver: apc
            query_cache_driver: apc
    
  • 将存储库附加到我的实体:

    /**
     * @ORM\Entity(repositoryClass="CommonBundle\Entity\Repository\CountryRepository")
     */
    class Country {
        ....
    
  • 在存储库类中编写一个方法来获取数据并缓存结果:

    public function getCountries() {
        $qb = $this->createQueryBuilder('c');
        $query = $qb->getQuery();
        $query->useResultCache(true, 3600, 'countries_cache');
        return $query->getResult();
    }
    

但是每当我重新加载页面时,查询都会执行,如分析器中所示(见下图):

我做错了什么?缓存仅适用于生产还是也适用于开发?不应该获取缓存结果而不是一次又一次地查询数据库?

【问题讨论】:

    标签: php symfony caching doctrine-orm doctrine


    【解决方案1】:

    您必须在 symfony 配置中为结果启用缓存:

    doctrine:
        orm:        
            metadata_cache_driver: apc # or memcache
            result_cache_driver: apc   # or memcache
            query_cache_driver: apc    # or memcache
    

    然后在每个需要缓存的请求上,调用

    $query->useResultCache(true)

    此处提供更多高级选项:http://docs.doctrine-project.org/en/2.0.x/reference/caching.html#result-cache

    【讨论】:

      【解决方案2】:

      EntityRepository API 不允许使用 find* 方法启用 ResultCache。

      您必须使用 QueryBuilder 和/或 DQL 请求。

      我写了一篇关于Doctrine缓存的文章,也许对你有帮助:http://blog.alterphp.com/2014/05/doctrine2-optimization-with-apc-cache.html

      【讨论】:

      • 你能看看我的版本吗?我的步骤有问题,或者我错过了一些东西
      • 我不确定工具栏对于测试缓存是否可信,也许它不会隐藏缓存的查询...您应该在 2 个请求之间更改数据库中的数据以测试缓存。
      猜你喜欢
      • 2011-04-03
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多