【问题标题】:How to store an array to the cache in Symfony?如何在 Symfony 中将数组存储到缓存中?
【发布时间】:2020-07-26 18:35:08
【问题描述】:

我有一个要从数据库显示的数组,经过许多业务实施后,我需要 1~2 分钟的时间来获得最终输出。因此,在使用 UI 进行测试时,这个过程让我很烦。所以我决定将这个最终数组存储到缓存中。我尝试使用以下代码行将myArray 存储到缓存中。

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$cache = new FilesystemAdapter();
// The callable will only be executed on a cache miss.
$output = $cache->get('my_cache_key', function (ItemInterface $item) use ($myArray) {
    $item->expiresAfter(7200);

    return $this->serializer->provideSerializer()->serialize($myArray, 'json');
});

我认为从缓存读取时应该更快,但加载数据仍然需要相同的时间。

谁能帮助我如何将我的数组存储到缓存中,以便下次加载更快。

谢谢。

【问题讨论】:

    标签: php caching symfony4


    【解决方案1】:

    您应该按照documentation 将$myArray 数据检索放入您的回调中,并且不要通过通过use 将其传入,因为这意味着它的检索是在缓存运行周期之外完成的。第 11 行提到应该在回调内部进行大量计算(或者,在您的情况下,应该对值进行冗长的数据库检索)。

    在你的情况下应该是这样的

    $output = $cache->get('my_cache_key', function (ItemInterface $item) {
    $item->expiresAfter(7200);
    
    // Your lengthy database query that retrieves data to be cached
    return $this->getDoctrine()
        ->getRepository(MyClass::class)
        ->find($id);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 2012-02-12
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多