Laravel - 通过频繁更新来缓存雄辩

Sta*_*wed 1 php caching redis laravel eloquent

是否可以在经常修改的对象上使用缓存?例如,假设我们有一个BlogPost对象,并且有一个频繁更改的num_of_views列(以及其他列).是否可以在缓存和数据库中更新num_of_views字段,而不会破坏缓存对象并重新创建它?我可以手动完成,但我担心同步问题.

Ant*_*iro 5

是的.我不知道你是如何做缓存的,但你可以随时替换缓存实例:

public function updatePost($post_id, $num_of_views)
{
    if (Cache::has('POST.'.$post_id))
    {
        $post = Cache::get('POST.'.$post_id);
    }
    else
    {
        $post = Post::find($post_id);
    }

    $post->num_of_views = $num_of_views;

    $post->save();

    Cache::put('POST.'.$post_id, $post);
}
Run Code Online (Sandbox Code Playgroud)