引自免费微信小程序:皆我百晓生
看起来您想要实现的是当用户关闭窗口时清除其在 Redis 中的相关会话数据,包括从其他用户那里接收到的消息的未读计数。首先,让我们分析一下现有的代码和可能的问题。
-
clearAllMsg函数中的问题:- 在遍历
$fromFriendHashKey和$toFriendHashKey时,使用了错误的数据结构。在 JavaScript 中,您应该使用Object.keys()方法来获取对象的键,而不是直接使用for...in循环。 - 您没有调用
clearAllMsg函数,所以它不会执行。确保在适当的地方调用这个方法,比如在onClose函数里。
- 在遍历
-
前端代码问题:
- 使用
for...in循环遍历 JavaScript 对象时,可能会包含非可枚举属性,因此推荐使用Object.keys()或Object.entries()来遍历对象的键值对。
- 使用
-
Redis 数据存储问题:
- 如果您确认 Redis 中确实有数据,但是在使用
keys *命令时找不到数据,可能是因为键前缀不正确,或者数据在其他数据库实例中。
- 如果您确认 Redis 中确实有数据,但是在使用
根据上述分析,我将提供修改后的代码片段:
首先,在 clearAllMsg 函数中使用正确的键访问方式:
private static function clearAllMsg($redis, $sn) {
$userNames = $redis->hKeys($sn . ':user');
foreach ($userNames as $userName) {
$fromFriendHashKey = $sn . ':friend:' . $userName;
$toFriendHashKey = $sn . ':friend:' . $userName;
$fromFriends = $redis->hGetAll($fromFriendHashKey);
$toFriends = $redis->hGetAll($toFriendHashKey);
foreach (array_keys($fromFriends) as $toUserName) {
$friend = json_decode($fromFriends[$toUserName], true);
if (isset($friend['unread'])) {
$friend['unread'] = 0;
$redis->hSet($fromFriendHashKey, $toUserName, json_encode($friend, JSON_UNESCAPED_UNICODE));
}
}
foreach (array_keys($toFriends) as $fromUserName) {
$friend = json_decode($toFriends[$fromUserName], true);
if (isset($friend['unread'])) {
$friend['unread'] = 0;
$redis->hSet($toFriendHashKey, $fromUserName, json_encode($friend, JSON_UNESCAPED_UNICODE));
}
}
}
return true;
}
接下来,在 onClose 函数中调用 clearAllMsg:
public static function onClose($client_id, $message) {
RedisHelper::clearAllMsg(Redis::connection(), $_SESSION['sn']);
}
对于前端部分,由于您没有提供具体的前端框架或库,我将以纯 JavaScript 为例:
function clearUnreadMessages(fromFriendHashKey, toFriendHashKey) {
for (const key of Object.keys(fromFriendHashKey)) {
console.log("Key: " + key + ", Value: " + fromFriendHashKey[key]);
}
for (const key of Object.keys(toFriendHashKey)) {
console.log("Key: " + key + ", Value: " + toFriendHashKey[key]);
}
}
// 在适当的位置调用此函数,例如用户关闭页面事件处理程序中
window.addEventListener('beforeunload', () => {
const fromFriendHashKey = ...; // 获取前端保存的 fromFriendHashKey 数据
const toFriendHashKey = ...; // 获取前端保存的 toFriendHashKey 数据
clearUnreadMessages(fromFriendHashKey, toFriendHashKey);
});
关于 Redis 数据的查找,确保您在正确的数据库实例中查询,并且键前缀匹配正确。您可以尝试在 Redis 客户端中指定数据库编号:
redis-cli -h 127.0.0.1 -p 6379 -n keys *
其中 应替换为您的 Redis 数据库编号。
如果您仍然遇到问题,请提供更多关于前端如何保存和使用 Redis 键以及用户会话信息的细节,以便我能提供更精确的帮助。
