使用redis缓存用户数据和聊天记录 Chat.php
<?php
/**
* @author <fl140125@gmail.com>
* Class Chat
*/
class Chat
{
/**
* @var Redis $redisClient
*/
protected $redisClient;
/**
* @var string $hashKey
*/
protected $hashKey = 'unread_';
/**
* Chat constructor.
*/
public function __construct()
{
$this->redisClient = new Redis();
$this->redisClient -> connect('127.0.0.1', 6379);
}
/**
* TODO:缓存用户聊天记录
* @param $from
* @param $to
* @param $room_id
* @param $message
* @return bool|int
*/
public function setChatMsgLists($from, $to, $room_id, $message)
{
$value = str_replace('\\', '', json_encode($message, JSON_UNESCAPED_UNICODE));
$keyName = $to == 'all' ? 'receive_all_'.$room_id : "receive_{$from}_{$to}";
return $this ->redisClient-> lPush($keyName, $value);
}
/**
* TODO:获取聊天记录
* @param $from
* @param $to
* @param $room_id
* @param int $page
* @param int $limit
* @return array
*/
public function getChatMsgLists($from, $to, $room_id, $page = 1, $limit = 19)
{
$message = array();
$time = array();
$offset = $limit * ($page - 1) ;
//群聊消息
if (!empty($room_id)) {
$recName = 'receive_all_'.$room_id;
$num = $this->getMsgLen($recName);