繁体   English   中英

使用 Redis 和 MySQL 加载和更新数据的最佳做法是什么?

[英]What is the best practice to load and update data using Redis and MySQL?

我正在使用 Redis 作为缓存层,我想知道什么是最佳实践或如何与 DB(在本例中为 MySQL)一起正确使用它。

这里我有一个用户仪表板 function 的示例:

public function updateDashboardUser(Request $request) {

        $user = app('redis')->hGetAll($request->userID); //Get data from cache

        if ($user) { //if there is data use this

            $id = $user['id'];
            $name = $user['name'];

        } else { //otherwise use this
            $user = User::select('id', 'name')->where('id', '=', $request->userID)->first();

            $id = $user->id;
            $name = $user->name;

        }

        return response()->json(['id' => $id, 'name' => $name], 200);

    }

但是,即使缓存中的$user可能为空,也永远不会以某种方式到达此 else 语句。 有一个更好的方法吗?

同样在更新时......当其中一个中的数据发生更改时,是否有更好的方法来自动更新(缓存和数据库)。

public function editDashboard(Request $request) {
        $user = Route::find($request->userID);

        $user->name = $request->name;
        $user->save();

        $cacheEdit = app('redis')->hSet($user->id, 'name', $request->name);

        return response()->json(['status' => '200'], 200);
    }

目前我这样做,但有时可能只有其中一个被更改,然后缓存数据(反之亦然,数据库数据)没有同步/更新。

这是我对 Redis 和一般缓存的第一次体验,因此不胜感激。

  • Instead of directly using Redis API, you should use Laravel cache API instead, it allows some abstraction and you don't even need to know which is the underlying cache.

  • 通过使用 Eloquent 而不是查询生成器,您可以解锁一些非常强大的功能,例如 model 事件。 例如,在您的User model 中:

protected static function booted()
{
    parent::booted();

    $cache = app('cache');

    static::updated(function ($user) use ($cache) {
        $cacheKey = $user->getCacheKey();
        if ($cache->has($cacheKey) {
            $cache->put($cacheKey, $user, 30); //30 is the life duration of this value in cache, you're free to change it
        }
    });

    static::deleted(function ($user) use ($cache) {
        $cache->forget($user->getCacheKey());
    });
}

public function getCacheKey()
{
    return 'users.' . $this->getKey();
}

每当您使用 Eloquent 更新或删除User时,Laravel 会自动调用这些“事件挂钩”。

然后,它允许您流利地执行此操作:

use App\User;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\Cache\Repository as Cache;

public function updateDashboardUser(Request $request, Cache $cache, ResponseFactory $responseFactory)
{
    $id = $request->userID;

    $user = $cache->remember('users.' . $id, 30, function () use ($id) {
        return User::findOrFail($id);
    });

    return $responseFactory->json($user->only(['id', 'name']), 200);
}

例如这里提到的https://laravel.com/docs/7.x/cache#retrieving-items-from-the-cache ,您可以使用remember (或rememberForever )从缓存中检索某些内容并自动回退到闭包中如果没有找到。 然后findOrFail将从数据库中检索它并最终抛出Illuminate\Database\Eloquent\ModelNotFoundException ,因为发送成功的响应没有任何意义。 我还通过在合同(Laravel 接口)上使用依赖注入来替换您的助手,例如response ,这是最干净的做法。

https://laravel.com/docs/7.x/contracts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM