php redis 处理websocket聊天记录的实例代码
具体代码如下所示:
redis=newRedis(); $this->redis->connect('127.0.0.1','6379'); $this->redis->auth('***cnblogs.com/handle'); } /* 发送消息时保存聊天记录 *这里用的redis存储是list数据类型 *两个人的聊天用一个list保存 * *@from消息发送者id *@to消息接受者id *@meassage消息内容 * *返回值,当前聊天的总聊天记录数 */ publicfunctionsetChatRecord($from,$to,$message){ $data=array('from'=>$from,'to'=>$to,'message'=>$message,'sent'=>time()/*,'recd'=>0*/); $value=json_encode($data); //生成json字符串 $keyName='rec:'.$this->getRecKeyName($from,$to); //echo$keyName; $res=$this->redis->lPush($keyName,$value); if(!$this->checkUserReadable){//消息接受者无法立刻查看时,将消息设置为未读 $this->cacheUnreadMsg($from,$to); } return$res; } /* *获取聊天记录 *@from消息发送者id *@to消息接受者id *@num获取的数量 * *返回值,指定长度的包含聊天记录的数组 */ publicfunctiongetChatRecord($from,$to,$num){ $keyName='rec:'.$this->getRecKeyName($from,$to); //echo$keyName; $recList=$this->redis->lRange($keyName,0,(int)($num)); return$recList; } /* *当用户上线时,或点开聊天框时,获取未读消息的数目 *@user用户id * *返回值,一个所有当前用户未读的消息的发送者和数组 *数组格式为‘消息发送者id'=>‘未读消息数目' * */ publicfunctiongetUnreadMsgCount($user){ return$this->redis->hGetAll('unread_'.$user); } /* *获取未读消息的内容 *通过未读消息数目,在列表中取得最新的相应消息即为未读 *@from消息发送者id *@to消息接受者id * *返回值,包括所有未读消息内容的数组 * * */ publicfunctiongetUnreadMsg($from,$to){ $countArr=$this->getUnreadMsgCount($to); $count=$countArr[$from]; $keyName='rec:'.$this->getRecKeyName($from,$to); return$this->redis->lRange($keyName,0,(int)($count)); } /* *将消息设为已读 *当一个用户打开另一个用户的聊天框时,将所有未读消息设为已读 *清楚未读消息中的缓存 *@from消息发送者id *@to消息接受者id * *返回值,成功将未读消息设为已读则返回true,没有未读消息则返回false */ publicfunctionsetUnreadToRead($from,$to){ $res=$this->redis->hDel('unread_'.$to,$from); return(bool)$res; } /* *当用户不在线时,或者当前没有立刻接收消息时,缓存未读消息,将未读消息的数目和发送者信息存到一个与接受者关联的hash数据中 * *@from发送消息的用户id *@to接收消息的用户id * *返回值,当前两个用户聊天中的未读消息 * */ privatefunctioncacheUnreadMsg($from,$to){ return$this->redis->hIncrBy('unread_'.$to,$from,1); } /*生成聊天记录的键名,即按大小规则将两个数字排序 *@from消息发送者id *@to消息接受者id * * */ privatefunctiongetRecKeyName($from,$to){ return($from>$to)?$to.'_'.$from:$from.'_'.$to; } } /* *下面为测试用的代码,伪造数据模拟场景 *假定有两个用户id为2和3,2向3发送消息 * $chat=newchatClass(); $chat->checkUserReadable=true; for($i=0;$i<20;$i++){ $chat->setChatRecord('2','3','message_'.$i); } echo'get20chatrecords'; $arr=$chat->getChatRecord('2','3',20); for($j=0;$j'; } $chat->checkUserReadable=false; for($m=0;$m<5;$m++){ $chat->setChatRecord('2','3','message_'.$m); } echo""; $umsg_1=$chat->getUnreadMsgCount(3); echo"Unreadmessagecounts"; echo""; print_r($umsg_1); echo"Unreadmessagecontent"; $umsgContent=$chat->getUnreadMsg(2,3); for($n=0;$n '; } echo""; $chat->setUnreadToRead(2,3); $umsg_2=$chat->getUnreadMsgCount(3); echo""; echo"Unreadmessagecounts"; echo""; print_r($umsg_2); * */ ?>
总结
以上所述是小编给大家介绍的phpredis处理websocket聊天记录的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。