我有一个从数据库中显示的数组,在许多业务实现之后,这需要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');
});我认为从缓存读取应该更快,但加载数据仍然需要相同的时间。
有没有人可以帮我把我的数组存储到缓存中,这样下次加载速度就会更快。
谢谢。
发布于 2020-04-14 13:25:11
您应该按照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);
});https://stackoverflow.com/questions/61200804
复制相似问题