Laravel 选择性缓存

编程入门 行业动态 更新时间:2024-10-12 16:26:47
本文介绍了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.

以这个简化函数为例:

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

And of course you could use Cache::put($key, $data, $minutes); instead of forever

更多推荐

Laravel 选择性缓存

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

发布评论

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

>www.elefans.com

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