Laravel选择性缓存

编程入门 行业动态 更新时间:2024-10-12 12:24:53
本文介绍了Laravel选择性缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Laravel 4框架开发我的第一个应用程序(顺便说一下,使用它进行设计很有趣).对于一个组件,有一个AJAX请求来查询外部服务器.问题是,我只想在成功的时间内将这些响应缓存 .

I'm developing one of my first applications with the Laravel 4 framework (which, by the way, is a joy to design with). For one component, there is an AJAX request to query an external server. The issue is, I want to cache these responses for a certain period of time only if they are successful.

Laravel具有Cache :: remember()函数,但问题在于似乎没有不存储缓存的失败"模式(至少在其文档中没有描述).

Laravel has the Cache::remember() function, but the issue is there seems to be no "failed" mode (at least, none described in their documentation) where a cache would not be stored.

例如,使用此简化功能:

For example, take this simplified function:

try { $server->query(); } catch (Exception $e) { return Response::json('error', 400); }

我想在此输出上使用Cache :: remember,但如果未引发任何异常,则仅使用 .我可以想到一些比这优雅的方法,但是我认为Laravel这么有说服力的框架会是更好的方法.有什么帮助吗?谢谢!

I would like to use Cache::remember on the output of this, but only if no Exception was thrown. I can think of some less-than-elegant ways to do this, but I would think that Laravel, being such an... eloquent... framework, would have a better way. Any help? Thanks!

推荐答案

这对我有用:

if (Cache::has($key)) { $data = Cache::get($key); } else { try { $data = longQueryOrProcess($key); Cache::forever($key, $data); // only stored when no error } catch (Exception $e) { // deal with error, nothing cached } }

当然可以使用Cache::put($key, $data, $minutes);代替forever

更多推荐

Laravel选择性缓存

本文发布于:2023-10-27 10:44:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:选择性   缓存   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!