PHP 代码 清理 redis 消息问题

32 天前
 aaabababa
public static function onClose($client_id, $message) {
RedisHelper::clearallmsg($_SESSION['sn']);
}


定义一个窗口关闭函数,引用了清理 redis 消息


private static function getUser($redis, $sn, $data, $add = false) {
if ( $add ) {
$data = [
//'id' => $data['id'],
'name' => $data['name'],
'passwd' => $data['passwd'],
'img' => $data['img'],
];

return $redis->hset($sn .':user', $data['name'], json_encode($data, JSON_UNESCAPED_UNICODE));
}

$data = $redis->hget($sn .':user', $data['name']);
return json_decode($data, true);
}


找了 AI 回复

private static function clearAllMsg($redis, $sn) {
// 获取所有用户的名称列表
$userNames = $redis->hKeys($sn . ':user');

// 遍历所有用户
foreach ($userNames as $userName) {
// 构造该用户的“from”好友关系哈希表的键
$fromFriendHashKey = $sn . ':friend:' . $userName;

// 获取该用户的所有“from”好友
$fromFriends = $redis->hGetAll($fromFriendHashKey);

// 遍历“from”好友,并清空未读消息计数
foreach ($fromFriends as $toUserName => $friendData) {
$friend = json_decode($friendData, true);
if (isset($friend['unread'])) {
$friend['unread'] = 0;
$redis->hSet($fromFriendHashKey, $toUserName, json_encode($friend, JSON_UNESCAPED_UNICODE));
}
}

// 构造该用户的“to”好友关系哈希表的键(理论上与“from”是相同的,但为了完整性还是列出)
$toFriendHashKey = $sn . ':friend:' . $userName; // 注意:这里和 from 是一样的,因为好友关系是双向的

// 获取该用户作为“to”的所有好友关系(通常这些与“from”是镜像的,但为了安全起见还是检查一遍)
$toFriends = $redis->hGetAll($toFriendHashKey);

// 遍历“to”好友,并清空未读消息计数(理论上这一步是多余的,因为数据是共享的)
foreach ($toFriends as $fromUserName => $friendData) {
$friend = json_decode($friendData, true);
if (isset($friend['unread'])) {
$friend['unread'] = 0;
$redis->hSet($toFriendHashKey, $fromUserName, json_encode($friend, JSON_UNESCAPED_UNICODE));
}
}
}

// 返回操作成功的信息
return true;
}



但试了下,函数 clearAllMsg 不起作的。
1015 次点击
所在节点    PHP
2 条回复
0576coder
32 天前
如果好友多的话,hGetAll 会卡,
初步看了代码,感觉没啥大问题啊,你把 hset 的 key 跟 value 在执行前打印下看看
aaabababa
25 天前
@0576coder 在前端加了代码,打印不出来的

for (var key in fromFriendHashKey) {
console.log("Key: " + key + ", Value: " + fromFriendHashKey[key]);
}

// 遍历并打印出$toFriendHashKey 的所有值
for (var key in toFriendHashKey) {
console.log("Key: " + key + ", Value: " + toFriendHashKey[key]);
}

然后在服务器连接 redis-cli -h 127.0.0.1 -p 6379
keys *
也没有数据。但是前端是可以登陆看到消息记录的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1036868

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX