在 Redis 中更新 LIST/SET 上的特定记录的正确方法

Proper way to update specific record on the LIST/SET in Redis

我计划使用 Redis 作为我的 PHP API 的第二个 class 数据库(用于 PHP 和 Redis 连接的 Predis),我的主数据库是MySQL。我是新手,我想知道我是走在正确的道路上还是完全错了。

我将对所有 "SELECT" 或检索查询使用 Redis,而不是从 MySQL 获取它。这是示例流程。

我有一个用户在其他 table 上有多个记录(1:很多)。表A包含所有用户,表B包含所有用户的所有体验记录。

**TableA**
UserID - 1234
UserID - 4567
UserID - 7890

-------------------------------------------------------


**TableB**
ExperienceID - 1    |   UserID - 1234   |   Experience - Waiter
ExperienceID - 2    |   UserID - 1234   |   Experience - Chef
ExperienceID - 3    |   UserID - 4567   |   Experience - Developer
ExperienceID - 4    |   UserID - 4567   |   Experience - Technician
ExperienceID - 5    |   UserID - 4567   |   Experience - Support
ExperienceID - 6    |   UserID - 7890   |   Experience - Engineer
ExperienceID - 7    |   UserID - 7890   |   Experience - Engineer
ExperienceID - 8    |   UserID - 7890   |   Experience - Draftsman

这是我在 Redis 中的布局。

uid:1234:experience
uid:4567:experience
uid:7890:experience

记录体验命名空间内部

我使用 SADD 和 json 编码数据来设置

$userExperience1 = array(
    'id'            => 1,
    'user_id'       => 1234,
    'experience'    => 'Waiter'
);

$userExperience2 = array(
    'id'            => 2,
    'user_id'       => 1234,
    'experience'    => 'Chef'
);


$redis->sadd('uid:' . $userId . ':experience', json_encode($userExperience1));
$redis->sadd('uid:' . $userId . ':experience', json_encode($userExperience2));

我也试过使用 LIST

$redis->rpush('uid:' . $userId . ':experience', json_encode($userExperience1));
$redis->rpush('uid:' . $userId . ':experience', json_encode($userExperience2));

但是我不知道在redis上更新特定记录的正确方法,比如我只想更新用户1234的"Waiter"体验。

有什么建议或建议吗?谢谢大家。

对于集合,您没有其他选择,只能在应用程序级别迭代集合。

通过列表,您可以处理单个对象,只需将列表中的项目 ID 映射到体验 ID。像这样:

$listId = $redis->rpush('uid:' . $userId . ':experience', json_encode($userExperience1));
$redis->set('eid:' . $userExperience1['id'] . ':listId', $listId);

所以更新很简单:

$listId = $redis->get('eid:' . $newUserExperience['id'] . ':listId', $listId);
$redis->lset('uid:' . $userId . ':experience', $listId - 1, json_encode($newUserExperience));

但是如果您从列表中删除任何体验以保持地图同步,则需要格外小心。