V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
aaabababa
V2EX  ›  PHP

PHP 代码 清理 redis 消息问题

  •  
  •   aaabababa · 17 天前 · 783 次点击
    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 不起作的。
    2 条回复    2024-05-07 13:26:34 +08:00
    0576coder
        1
    0576coder  
       16 天前
    如果好友多的话,hGetAll 会卡,
    初步看了代码,感觉没啥大问题啊,你把 hset 的 key 跟 value 在执行前打印下看看
    aaabababa
        2
    aaabababa  
    OP
       9 天前
    @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 *
    也没有数据。但是前端是可以登陆看到消息记录的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1624 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:13 · PVG 01:13 · LAX 10:13 · JFK 13:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.