如何在Symfony中将数组存储到缓存中?

问题描述 投票:0回答:1

我有一个要从数据库中显示的数组,经过许多业务实现后,要花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个回答
0
投票

您应该根据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);
});
© www.soinside.com 2019 - 2024. All rights reserved.