PHP 代码 清理 redis 消息问题

查看 23|回复 0
作者: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 不起作的。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部