gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:17:00 25 4
gpt4 key购买 nike

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

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

我有一个用户在其他表上有多个记录 (1:many)。表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
  • 在 MySQL 上保存新体验,一旦成功,它将在 Redis 上推送相同的体验(以 redis 格式)。
  • 从 Redis 而不是 MySQL 获取/检索所有记录
  • 更新 MySQL 上的体验,一旦成功,它将更新 Redis 上的特定体验 ---> 我不知道如何在 Redis 上执行此操作而不在 PHP 上循环,如果我有的话,这不是个好主意巨大的记录列表 :(

这是我在 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));

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

关于php - 在 Redis 中更新 LIST/SET 上的特定记录的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45410598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com