SoFunction
Updated on 2025-03-08

php redis instance code for handling websocket chat history

The specific code is as follows:

<?phpini_set('display_errors', 'on');
class chatClass {
 private $redis;
 //This variable simulates the current status of the user, whether to log in, and whether it can be viewed public $checkUserReadable = false;
 //Constructor link redis database public function __construct() {
  $this -> redis = new Redis();
  $this -> redis -> connect('127.0.0.1', '6379');
  $this -> redis -> auth('***/handle');
 }
 /*
  Save chat history when sending a message
  * The redis storage used here is the list data type
  * Two people's chats are saved in a list
  *
  * @from message sender id
  * @to Message Recipient ID
  * @meassage message content
  *
  * Return value, total number of chat records for the current chat
  */
 public function setChatRecord($from, $to, $message) {
  $data = array('from' => $from, 'to' => $to, 'message' => $message, 'sent' => time()/*, 'recd' => 0*/);
  $value = json_encode($data);
  //Generate json string  $keyName = 'rec:' . $this -> getRecKeyName($from, $to);
  //echo $keyName;
  $res = $this -> redis -> lPush($keyName, $value);
  if (!$this -> checkUserReadable) {// When the message recipient cannot view it immediately, set the message to not read   $this -> cacheUnreadMsg($from, $to);
  }
  return $res;
 }
 /*
  * Get chat history
  * @from message sender id
  * @to Message Recipient ID
  * @num Number of obtained
  *
  * Return value, specified length array containing chat records
  */
 public function getChatRecord($from, $to, $num) {
  $keyName = 'rec:' . $this -> getRecKeyName($from, $to);
  //echo $keyName;
  $recList = $this -> redis -> lRange($keyName, 0, (int)($num));
  return $recList;
 }
 /*
  * When the user is online, or when the chat box is opened, get the number of unread messages
  * @user User ID
  *
  * Return value, sender and array of messages not read by the current user
  * The array format is 'Message sender id'=>'Number of unread messages'
  *
  */
 public function getUnreadMsgCount($user) {
  return $this -> redis -> hGetAll('unread_' . $user);
 }
 /*
  * Get the content of unread messages
  * The number of unread messages is obtained, and the latest corresponding message in the list is unread
  * @from message sender id
  * @to Message Recipient ID
  *
  * Return value, array including all unread message content
  *
  *
  */
 public function getUnreadMsg($from, $to) {
  $countArr = $this -> getUnreadMsgCount($to);
  $count = $countArr[$from];
  $keyName = 'rec:' . $this -> getRecKeyName($from, $to);
  return $this -> redis -> lRange($keyName, 0, (int)($count));
 }
 /*
  * Set the message to read
  * When one user opens another user's chat box, set all unread messages to read
  * Clear cache in unread messages
  * @from message sender id
  * @to Message Recipient ID
  *
  * Return value, if the unread message is successfully set to read, it will return true, if there is no unread message, it will return false
  */
 public function setUnreadToRead($from, $to) {
  $res = $this -> redis -> hDel('unread_' . $to, $from);
  return (bool)$res;
 }
 /*
  * When the user is not online, or when the message is not received immediately, the unread message is cached, and the number of unread messages and sender information is stored in a hash data associated with the recipient.
  *
  * @from The user id of the message
  * @to The user id that received the message
  *
  * Return value, unread messages in the current chat between two users
  *
  */
 private function cacheUnreadMsg($from, $to) {
  return $this -> redis -> hIncrBy('unread_' . $to, $from, 1);
 }
 /*The key name of the chat record is generated, that is, the two numbers are sorted by the size rule
  * @from message sender id
  * @to Message Recipient ID
  *
  *
  */
 private function getRecKeyName($from, $to) {
  return ($from > $to) ? $to . '_' . $from : $from . '_' . $to;
 }
}
/*
 * The following is the test code, which fakes data and simulates the scenario
 * Assume that there are two users with ids 2 and 3, 2 sends a message to 3
 *
 $chat = new chatClass();
 $chat -> checkUserReadable = true;
 for ($i = 0; $i < 20; $i++) {
 $chat -> setChatRecord('2', '3', 'message_' . $i);
 }
 echo 'get 20 chat records</br>';
 $arr = $chat -> getChatRecord('2', '3', 20);
 for ($j = 0; $j < count($arr); $j++) {
 echo $arr[$j] . '</br>';
 }
 $chat -> checkUserReadable = false;
 for ($m = 0; $m < 5; $m++) {
 $chat -> setChatRecord('2', '3', 'message_' . $m);
 }
 echo "</br>";
 $umsg_1 = $chat -> getUnreadMsgCount(3);
 echo "Unread message counts ";
 echo "</br>";
 print_r($umsg_1);
 echo "Unread message content </br> ";
 $umsgContent = $chat -> getUnreadMsg(2, 3);
 for ($n = 0; $n < count($umsgContent); $n++) {
 echo $arr[$n] . '</br>';
 }
 echo "</br>";
 $chat -> setUnreadToRead(2, 3);
 $umsg_2 = $chat -> getUnreadMsgCount(3);
 echo "</br>";
 echo "Unread message counts ";
 echo "</br>";
 print_r($umsg_2);
 *
 */
?&gt;

Summarize

The above is the example code for php redis to handle websocket chat records introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!