Laravel选择性缓存 [英] Laravel Selective Caching

查看:91
本文介绍了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选择性缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆