优化代码

main
gzydong 2021-05-20 22:23:48 +08:00
parent 8fdf7ca16c
commit cad0468af7
20 changed files with 309 additions and 302 deletions

View File

@ -1,45 +0,0 @@
<?php
namespace App\Cache;
/**
* Class ApplyNumCache
*
* @package App\Cache
*/
class ApplyNumCache
{
const KEY = 'friend:apply:unread:num';
/**
* 获取好友未读申请数
*
* @param int $user_id 用户ID
* @return string
*/
public static function get(int $user_id)
{
return redis()->hget(self::KEY, strval($user_id));
}
/**
* 设置未读好友申请数自增加1
*
* @param int $user_id 用户ID
* @return int
*/
public static function setInc(int $user_id)
{
return redis()->hincrby(self::KEY, strval($user_id), 1);
}
/**
* 删除好友申请未读数
*
* @param int $user_id
*/
public static function del(int $user_id)
{
redis()->hdel(self::KEY, $user_id);
}
}

15
app/Cache/FriendApply.php Normal file
View File

@ -0,0 +1,15 @@
<?php
namespace App\Cache;
use App\Cache\Repository\HashRedis;
/**
* 好友申请未读数 - 缓存助手
*
* @package App\Cache
*/
class FriendApply extends HashRedis
{
public $name = 'friend-apply';
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Cache;
use App\Cache\Repository\HashRedis;
use App\Model\UsersFriend;
/**
* 好友备注 - 缓存助手
*
* @package App\Cache
*/
class FriendRemark extends HashRedis
{
public $name = 'friend-remark';
/**
* 设置好友备注缓存
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @param string $remark 好友备注
*/
public function save(int $user_id, int $friend_id, string $remark)
{
$this->add($this->_flag($user_id, $friend_id), $remark);
}
/**
* 获取好友备注
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @return string
*/
public function read(int $user_id, int $friend_id)
{
return $this->get($this->_flag($user_id, $friend_id));
}
/**
* 创建用户key
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @return string
*/
private function _flag(int $user_id, int $friend_id)
{
return "{$user_id}_{$friend_id}";
}
/**
* 加载所有数据进入缓存
*/
public function reload()
{
UsersFriend::select(['id', 'user1', 'user2', 'user1_remark', 'user2_remark'])->chunk(200, function ($rows) {
foreach ($rows as $row) {
$row->user1_remark && $this->save($row->user1, $row->user2, $row->user1_remark);
$row->user2_remark && $this->save($row->user2, $row->user1, $row->user2_remark);
}
});
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace App\Cache;
/**
* Class FriendRemarkCache
*
* @package App\Cache
*/
class FriendRemarkCache
{
const KEY = 'hash:user:friend:remark:cache';
/**
* 设置好友备注缓存
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @param string $remark 好友备注
*/
public static function set(int $user_id, int $friend_id, string $remark)
{
redis()->hset(self::KEY, "{$user_id}_{$friend_id}", $remark);
}
/**
* 获取好友备注
*
* @param int $user_id 用户ID
* @param int $friend_id 好友ID
* @return string
*/
public static function get(int $user_id, int $friend_id)
{
return redis()->hget(self::KEY, "{$user_id}_{$friend_id}") ?: '';
}
}

58
app/Cache/LastMessage.php Normal file
View File

@ -0,0 +1,58 @@
<?php
namespace App\Cache;
use App\Cache\Repository\HashRedis;
/**
* 聊天最新消息 - 缓存助手
*
* @package App\Cache
*/
class LastMessage extends HashRedis
{
public $name = 'last-message';
/**
* 保存最后一条缓存信息
*
* @param int $type 聊天类型[1:私信;2:群聊;]
* @param int $sender 发送者ID
* @param int $receive 接收者ID
* @param array $message
*/
public function save(int $type, int $sender, int $receive, array $message)
{
$this->add($this->flag($type, $sender, $receive), json_encode($message));
}
/**
* 读取最后一条缓存信息
*
* @param int $type 聊天类型[1:私信;2:群聊;3:机器人;]
* @param int $sender 发送者ID
* @param int $receive 接收者ID
* @return array
*/
public function read(int $type, int $sender, int $receive)
{
$message = $this->get($this->flag($type, $sender, $receive));
return $message ? json_decode($message, true) : [];
}
/**
* 获取 Hash 成员 key
*
* @return string
*/
public function flag(int $type, int $sender, int $receive)
{
// 群聊信息(非私信)发送者ID重置为零
if ($type == 2) $sender = 0;
[$sender, $receive] = $sender <= $receive ? [$sender, $receive] : [$receive, $sender];
return sprintf("%s_%s_%s", $type, $sender, $receive);
}
}

View File

@ -1,60 +0,0 @@
<?php
namespace App\Cache;
/**
* Class LastMsgCache
*
* @package App\Cache
*/
class LastMsgCache
{
/**
* 用户聊天或群聊的最后一条消息hash存储的hash名
*
* @param int $sender
* @return string
*/
private static function _name($sender = 0)
{
return $sender == 0 ? 'groups:chat:last.msg' : 'friends:chat:last:msg';
}
/**
* 获取hash key
*
* @param int $receive 接收者
* @param int $sender 发送者
* @return string
*/
private static function _key(int $receive, int $sender)
{
return $receive < $sender ? "{$receive}_{$sender}" : "{$sender}_{$receive}";
}
/**
* 设置好友之间或群聊中发送的最后一条消息缓存
*
* @param array $message 消息内容
* @param int $receive 接收者
* @param int $sender 发送者(注:若聊天消息类型为群聊消息 $sender 应设置为0)
*/
public static function set(array $message, int $receive, $sender = 0)
{
redis()->hset(self::_name($sender), self::_key($receive, $sender), serialize($message));
}
/**
* 获取好友之间或群聊中发送的最后一条消息缓存
*
* @param int $receive 接收者
* @param int $sender 发送者(注:若聊天消息类型为群聊消息 $sender 应设置为0)
* @return mixed
*/
public static function get(int $receive, $sender = 0)
{
$data = redis()->hget(self::_name($sender), self::_key($receive, $sender));
return $data ? unserialize($data) : null;
}
}

View File

@ -15,7 +15,7 @@ class HashRedis implements HashRedisInterface
private $prefix = 'rds:hash';
private $name = 'default';
public $name = 'default';
/**
* 获取 Hash
@ -42,10 +42,10 @@ class HashRedis implements HashRedisInterface
/**
* 设置 Hash
*
* @param string $key
* @param string $value
* @param string $key
* @param string|int $value
*/
public function add(string $key, string $value)
public function add(string $key, $value)
{
$this->redis()->hSet($this->getKeyName(), $key, $value);
}

View File

@ -15,7 +15,7 @@ class ListRedis implements ListRedisInterface
private $prefix = 'rds:list';
private $name = 'default';
public $name = 'default';
/**
* Push 队列任务

View File

@ -48,7 +48,7 @@ trait RedisTrait
*
* @return string
*/
private function getKeyName()
protected function getKeyName()
{
return $this->getCacheKey($this->name);
}

View File

@ -16,7 +16,7 @@ class SetRedis implements SetRedisInterface
private $prefix = 'rds:set';
private $name = 'default';
public $name = 'default';
/**
* 添加集合元素

View File

@ -11,7 +11,7 @@ class StreamRedis implements StreamRedisInterface
private $prefix = 'rds:stream';
private $name = 'default';
public $name = 'default';
/**
* 添加消息

View File

@ -15,7 +15,7 @@ class ZSetRedis implements ZSetRedisInterface
private $prefix = 'rds:zset';
private $name = 'default';
public $name = 'default';
/**
* 添加有序集合元素

78
app/Cache/UnreadTalk.php Normal file
View File

@ -0,0 +1,78 @@
<?php
namespace App\Cache;
use App\Cache\Repository\HashRedis;
/**
* 私信消息未读数 - 缓存助手
*
* @package App\Cache
*/
class UnreadTalk extends HashRedis
{
public $name = 'unread-talk';
/**
* 消息未读数自增
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
*/
public function increment(int $sender, int $receive)
{
$this->incr($this->flag($sender, $receive), 1);
}
/**
* 读取消息未读数
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
* @return int
*/
public function read(int $sender, int $receive)
{
return (int)$this->get($this->flag($sender, $receive));
}
/**
* 消息未读数清空
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
*/
public function reset(int $sender, int $receive)
{
$this->add($this->flag($sender, $receive), 0);
}
/**
* 获取 Hash 成员 key
*
* @return string
*/
public function flag(int $sender, int $receive)
{
return sprintf("%s_%s", $sender, $receive);
}
/**
* 读取指定用户的未读消息列表
*
* @param int $user_id 用户ID
* @return array
*/
public function reads(int $user_id)
{
$iterator = null;
$arr = [];
while ($elements = $this->redis()->hscan($this->getKeyName(), $iterator, '*_' . $user_id, 20)) {
foreach ($elements as $key => $value) {
$arr[explode('_', $key)[0]] = $value;
}
}
return $arr;
}
}

View File

@ -1,92 +0,0 @@
<?php
namespace App\Cache;
/**
* Class UnreadTalkCache
*
* @package App\Cache
*/
class UnreadTalkCache
{
const KEY = 'hash:unread_talk';
/**
* 设置用户未读消息(自增加1)
*
* @param int $user_id 用户ID
* @param string $friend_id 好友ID
* @return bool
*/
public function setInc(int $user_id, string $friend_id)
{
$num = $this->get($user_id, $friend_id) + 1;
return (bool)$this->redis()->hset($this->_key($user_id), $friend_id, $num);
}
/**
* 获取用户指定好友的未读消息数
*
* @param int $user_id 用户ID
* @param string $friend_id 好友ID
* @return int
*/
public function get(int $user_id, string $friend_id)
{
return (int)$this->redis()->hget($this->_key($user_id), $friend_id);
}
/**
* 获取用户未读消息列表
*
* @param int $user_id 用户ID
* @return mixed
*/
public function getAll(int $user_id)
{
return $this->redis()->hgetall($this->_key($user_id));
}
/**
* 清除用户指定好友的未读消息
*
* @param int $user_id 用户ID
* @param string $friend_id 好友ID
* @return bool
*/
public function del(int $user_id, string $friend_id)
{
return (bool)$this->redis()->hdel($this->_key($user_id), $friend_id);
}
/**
* 清除用户所有好友未读数
*
* @param int $user_id
* @return bool
*/
public function delAll(int $user_id)
{
return (bool)$this->redis()->del($this->_key($user_id));
}
/**
* 获取缓存key
*
* @param int $user_id 用户ID
* @return string
*/
private function _key(int $user_id)
{
return self::KEY . ":{$user_id}";
}
/**
* 获取Redis连接
*/
private function redis()
{
return redis();
}
}

View File

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Command;
use App\Cache\FriendRemark;
use App\Cache\LastMessage;
use App\Cache\Repository\HashRedis;
use App\Cache\Repository\ListRedis;
use App\Cache\Repository\LockRedis;
@ -11,6 +13,8 @@ use App\Cache\Repository\SetRedis;
use App\Cache\Repository\StreamRedis;
use App\Cache\Repository\StringRedis;
use App\Cache\Repository\ZSetRedis;
use App\Cache\UnreadTalk;
use App\Service\TalkService;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
@ -99,5 +103,29 @@ class TestCommand extends HyperfCommand
//
// return true;
//}, 'default', 'default');
//FriendRemark::getInstance()->reload();
//LastMessage::getInstance()->save(2, 1, 3, [
// 'created_at' => date('Y-m-d H:i:s'),
// 'content' => '那三级卡那那可是那那会计师哪安顺科技那发'
//]);
//var_dump(LastMessage::getInstance()->read(3, 6, 3));
//var_dump(UnreadTalk::getInstance()->read(1, 2));
//UnreadTalk::getInstance()->save(1, 2);
//$talk = UnreadTalk::getInstance();
//for ($i = 1; $i < 10; $i++) {
// for ($j = 1; $j < 10; $j++) {
// $talk->increment($i, $j);
// }
//}
//$model = new TalkService();
//$model->talks(2054);
var_dump(FriendRemark::getInstance()->read(2054,2055));
}
}

View File

@ -10,6 +10,8 @@
namespace App\Controller\Api\V1;
use App\Cache\FriendApply;
use App\Cache\FriendRemark;
use App\Model\UsersFriendsApply;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
@ -93,7 +95,7 @@ class ContactsController extends CController
}
// 好友申请未读消息数自增
ApplyNumCache::setInc(intval($params['friend_id']));
FriendApply::getInstance()->incr($params['friend_id'], 1);
// 判断对方是否在线。如果在线发送消息通知
if ($this->socketClientService->isOnlineAll(intval($params['friend_id']))) {
@ -224,9 +226,8 @@ class ContactsController extends CController
*/
public function getContactApplyUnreadNum()
{
$num = ApplyNumCache::get($this->uid());
return $this->response->success([
'unread_num' => $num ?: 0
'unread_num' => FriendApply::getInstance()->get(strval($this->uid()))
]);
}
@ -250,7 +251,7 @@ class ContactsController extends CController
$data = $this->contactsService->getContactApplyRecords($user_id, $page, $page_size);
ApplyNumCache::del($user_id);
FriendApply::getInstance()->rem(strval($user_id));
return $this->response->success($data);
}
@ -292,7 +293,8 @@ class ContactsController extends CController
return $this->response->fail('备注修改失败!');
}
FriendRemarkCache::set($user_id, intval($params['friend_id']), $params['remarks']);
FriendRemark::getInstance()->save($user_id, (int)$params['friend_id'], $params['remarks']);
return $this->response->success([], '备注修改成功...');
}
}

View File

@ -10,6 +10,8 @@
namespace App\Controller\Api\V1;
use App\Cache\LastMessage;
use App\Cache\UnreadTalk;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
@ -26,8 +28,6 @@ use App\Model\Group\Group;
use App\Service\TalkService;
use App\Service\UploadService;
use App\Amqp\Producer\ChatMessageProducer;
use App\Cache\LastMsgCache;
use App\Cache\UnreadTalkCache;
use App\Constants\SocketConstants;
/**
@ -45,12 +45,6 @@ class TalkController extends CController
*/
public $talkService;
/**
* @Inject
* @var UnreadTalkCache
*/
public $unreadTalkCache;
/**
* 获取用户对话列表
* @RequestMapping(path="list", methods="get")
@ -62,8 +56,8 @@ class TalkController extends CController
$user_id = $this->uid();
// 读取用户的未读消息列表
if ($result = $this->unreadTalkCache->getAll($user_id)) {
$this->talkService->updateUnreadTalkList($user_id, $result);
if ($list = UnreadTalk::getInstance()->reads($user_id)) {
$this->talkService->updateUnreadTalkList($user_id, $list);
}
// 获取聊天列表
@ -125,7 +119,7 @@ class TalkController extends CController
$data['name'] = $userInfo->nickname;
$data['avatar'] = $userInfo->avatar;
$data['unread_num'] = $this->unreadTalkCache->get($user_id, $result['friend_id']);
$data['unread_num'] = UnreadTalk::getInstance()->read($result['friend_id'], $user_id);
} else if ($result['type'] == 2) {
$groupInfo = Group::where('id', $result['group_id'])->first(['group_name', 'avatar']);
@ -133,7 +127,11 @@ class TalkController extends CController
$data['avatar'] = $groupInfo->avatar;
}
$records = LastMsgCache::get($result['type'] == 1 ? $result['friend_id'] : $result['group_id'], $result['type'] == 1 ? $user_id : 0);
$records = LastMessage::getInstance()->read(
(int)$result['type'], $user_id,
$result['type'] == 1 ? (int)$result['friend_id'] : (int)$result['group_id']
);
if ($records) {
$data['msg_text'] = $records['text'];
$data['updated_at'] = $records['created_at'];
@ -217,7 +215,7 @@ class TalkController extends CController
// 设置好友消息未读数
if ($params['type'] == 1) {
$this->unreadTalkCache->del($this->uid(), $params['receive']);
UnreadTalk::getInstance()->reset((int)$params['receive'], $this->uid());
}
return $this->response->success();
@ -329,7 +327,7 @@ class TalkController extends CController
if ($receive_user_ids) {
foreach ($receive_user_ids as $v) {
$this->unreadTalkCache->setInc($v['id'], $user_id);
UnreadTalk::getInstance()->increment($user_id, (int)$v['id']);
}
}
@ -540,10 +538,10 @@ class TalkController extends CController
'record_id' => $record_id
]));
LastMsgCache::set([
LastMessage::getInstance()->save((int)$params['source'], $user_id, (int)$params['receive_id'], [
'text' => '[图片消息]',
'created_at' => date('Y-m-d H:i:s')
], intval($params['receive_id']), $params['source'] == 1 ? $user_id : 0);
]);
return $this->response->success();
}
@ -588,10 +586,10 @@ class TalkController extends CController
'record_id' => $record_id
]));
LastMsgCache::set([
LastMessage::getInstance()->save((int)$params['source'], $user_id, (int)$params['receive_id'], [
'text' => '[代码消息]',
'created_at' => date('Y-m-d H:i:s')
], intval($params['receive_id']), $params['source'] == 1 ? $user_id : 0);
]);
return $this->response->success();
}
@ -653,10 +651,10 @@ class TalkController extends CController
'record_id' => $record_id
]));
LastMsgCache::set([
LastMessage::getInstance()->save((int)$params['source'], $user_id, (int)$params['receive_id'], [
'text' => '[文件消息]',
'created_at' => date('Y-m-d H:i:s')
], intval($params['receive_id']), $params['source'] == 1 ? $user_id : 0);
]);
return $this->response->success();
}
@ -711,10 +709,10 @@ class TalkController extends CController
'record_id' => $record_id
]));
LastMsgCache::set([
LastMessage::getInstance()->save((int)$params['source'], $user_id, (int)$params['receive_id'], [
'text' => '[表情包消息]',
'created_at' => date('Y-m-d H:i:s')
], intval($params['receive_id']), $params['source'] == 1 ? $user_id : 0);
]);
return $this->response->success();
}

View File

@ -3,7 +3,7 @@ declare(strict_types=1);
namespace App\Service;
use App\Cache\LastMsgCache;
use App\Cache\LastMessage;
use App\Model\Chat\ChatRecord;
use App\Model\Chat\ChatRecordsInvite;
use App\Model\Group\Group;
@ -133,8 +133,10 @@ class GroupService extends BaseService
return [false, 0];
}
// 设置群聊消息缓存
LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $insRes->id, 0);
LastMessage::getInstance()->save(2, $user_id, $insRes->id, [
'text' => '[入群通知]',
'created_at' => date('Y-m-d H:i:s')
]);
return [true, ['record_id' => $result->id, 'group_id' => $insRes->id]];
}
@ -269,7 +271,11 @@ class GroupService extends BaseService
return [false, 0];
}
LastMsgCache::set(['created_at' => date('Y-m-d H:i:s'), 'text' => '入群通知'], $group_id, 0);
LastMessage::getInstance()->save(2, $user_id, $group_id, [
'text' => '[入群通知]',
'created_at' => date('Y-m-d H:i:s')
]);
return [true, $result->id];
}

View File

@ -3,16 +3,15 @@
namespace App\Service;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Amqp\Producer;
use Swoole\Http\Response;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use App\Amqp\Producer\ChatMessageProducer;
use App\Cache\LastMsgCache;
use App\Cache\UnreadTalkCache;
use App\Model\Chat\ChatRecord;
use App\Model\Group\Group;
use App\Model\UsersFriend;
use App\Cache\LastMessage;
use App\Cache\UnreadTalk;
class MessageHandleService
{
@ -22,12 +21,6 @@ class MessageHandleService
*/
private $socketClientService;
/**
* @Inject
* @var UnreadTalkCache
*/
private $unreadTalkCache;
/**
* 对话消息
*
@ -73,18 +66,16 @@ class MessageHandleService
if (!$result) return;
// 判断是否私聊
if ($data['source_type'] == 1) {
if ($result->source == 1) {
// 设置好友消息未读数
$this->unreadTalkCache->setInc(intval($result->receive_id), strval($result->user_id));
UnreadTalk::getInstance()->increment($result->user_id, $result->receive_id);
}
// 缓存最后一条消息
LastMsgCache::set([
// 缓存最后一条聊天消息
LastMessage::getInstance()->save($result->source, $result->user_id, $result->receive_id, [
'text' => mb_substr($result->content, 0, 30),
'created_at' => $result->created_at
], (int)$data['receive_user'],
$data['source_type'] == 1 ? (int)$data['send_user'] : 0
);
]);
// 推送消息
push_amqp(new ChatMessageProducer('event_talk', [

View File

@ -2,21 +2,21 @@
namespace App\Service;
use App\Cache\FriendRemarkCache;
use App\Cache\LastMsgCache;
use App\Cache\UnreadTalkCache;
use Exception;
use App\Model\User;
use App\Model\UsersChatList;
use App\Model\UsersFriend;
use App\Model\Group\Group;
use App\Model\Chat\ChatRecord;
use App\Model\Chat\ChatRecordsCode;
use App\Model\Chat\ChatRecordsFile;
use App\Model\Chat\ChatRecordsForward;
use App\Model\Chat\ChatRecordsInvite;
use App\Model\Group\Group;
use App\Model\User;
use App\Model\UsersChatList;
use App\Model\UsersFriend;
use App\Traits\PagingTrait;
use Exception;
use Hyperf\DbConnection\Db;
use App\Cache\FriendRemark;
use App\Cache\LastMessage;
use App\Cache\UnreadTalk;
class TalkService extends BaseService
{
@ -68,10 +68,10 @@ class TalkService extends BaseService
if ($item['type'] == 1) {
$data['name'] = $item['nickname'];
$data['avatar'] = $item['user_avatar'];
$data['unread_num'] = make(UnreadTalkCache::class)->get($user_id, $item['friend_id']);
$data['unread_num'] = UnreadTalk::getInstance()->read((int)$item['friend_id'], $user_id);
$data['online'] = $socketFDService->isOnlineAll($item['friend_id'], $runIdAll);
$remark = FriendRemarkCache::get($user_id, $item['friend_id']);
$remark = FriendRemark::getInstance()->read($user_id, (int)$item['friend_id']);
if ($remark) {
$data['remark_name'] = $remark;
} else {
@ -81,7 +81,7 @@ class TalkService extends BaseService
if ($info) {
$data['remark_name'] = ($info->user1 == $item['friend_id']) ? $info->user2_remark : $info->user1_remark;
FriendRemarkCache::set($user_id, $item['friend_id'], $data['remark_name']);
FriendRemark::getInstance()->save($user_id, (int)$item['friend_id'], $data['remark_name']);
}
}
} else {
@ -89,7 +89,7 @@ class TalkService extends BaseService
$data['avatar'] = $item['group_avatar'];
}
$records = LastMsgCache::get($item['type'] == 1 ? $item['friend_id'] : $item['group_id'], $item['type'] == 1 ? $user_id : 0);
$records = LastMessage::getInstance()->read((int)$item['type'], $user_id, $item['type'] == 1 ? (int)$item['friend_id'] : (int)$item['group_id']);
if ($records) {
$data['msg_text'] = $records['text'];
$data['updated_at'] = $records['created_at'];