簡體   English   中英

整合Symfony2和Redis

[英]Integrating Symfony2 and Redis

我正在嘗試將Redis與我的Symfony API集成在一起,我發現了這個捆綁包: RedisBundle

我安裝並配置它,以便可以像config.yml這樣緩存Doctrine:

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

        metadata_cache_driver: redis
        # enable query caching
        query_cache_driver: redis

snc_redis:
# configure predis as client
clients:
    default:
        type: predis
        alias: default
        dsn: redis://localhost
    doctrine:
        type: predis
        alias: doctrine
        dsn: redis://localhost
# configure doctrine caching
doctrine:
    metadata_cache:
        client: doctrine
        entity_manager: default
        document_manager: default
    result_cache:
        client: doctrine
        entity_manager: [default]
    query_cache:
        client: doctrine
        entity_manager: default

在我的FetchBookRepository中,我嘗試在其中使用RedisCache:

<?php

namespace BooksApi\BookBundle\Repositories;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\QueryException;

use Snc\RedisBundle\Doctrine\Cache\RedisCache;
use Predis\Client;

class FetchBookRepository
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(
        EntityManager $entityManager
    ){
        $this->em = $entityManager;
    }

    /**
     * @param $id
     * @return null|object
     * @throws QueryException
     */
    public function fetchBook($id)
    {

        $predis = new RedisCache();
        $predis->setRedis(new Client);
        $cache_lifetime= 3600;

        try {
            $book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
                ->find($id);

        } catch (\Exception $ex) {
            $this->em->close();
            throw new QueryException('003', 502);
        }

        return $book;
    }
}

我調用了RedisCahce和Client類,但是現在如何在查詢中使用它。 關於Symfony和Redis,我在Google上找不到很多。

更新:

當我使用redis-cli並輸入MONITOR時,我得到以下輸出:

1454337749.112055 [0 127.0.0.1:60435] "GET" "[BooksApi\\BookBundle\\Entity\\BooksEntity$CLASSMETADATA][1]"

您的Redis配置看起來不錯。 您正在使用Redis緩存Meatada(有關實體映射等的文檔)和查詢(DQL到SQL)。

要將Redis用作結果緩存,您必須編寫自定義查詢並定義其可緩存。 請遵循Doctrine手冊http://docs.doctrine-project.org/en/latest/reference/caching.html#result-cache和此GitHub問題https://github.com/snc/SncRedisBundle/issues/77

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM