使用存储在缓存/存储而不是数据库中的数据

时间:2019-01-20 23:24:09

标签: laravel

我当时正在考虑使用缓存/存储来存储api路由的源代码,但更新不会太多。我的意思是我想每分钟更新一次存储的数据(示例),并且我的路线将使用该数据作为源,而不是数据库作为源。它将减少数据库查询。我想的很好吗?如何在Laravel中实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以设置Laravel支持的memcached实例。 Laravel缓存documentation是开始学习如何为memcached设置缓存驱动程序的好地方。设置完成后,您的逻辑可能看起来像这样:

if (Cache::has('key')) {
    //your key exists in the cache. get it.
    $value = Cache::get('key');

    //and use it
    useMyValue($value);
}
else
{
    //the cache does not contain the key you are looking for
    //you can get it from the DB and cache it.
    //the next time your function runs it will get the value from cache instead
    //of reading from the db
    $value = Cache::get('key', function () {
        return DB::table(...)->get();
    });
    //and use your value now like normal
    useMyValue()
}