TeamTalk知识点梳理一(单聊)


在这里插入图片描述

db_proxy_server

db_proxy_server数据库代理服务。

db_proxy_server reactor响应处理流程

  1. 数据入口 reactor CProxyConn:: HandlePduBuf
  2. 怎么初始化epoll+线程池
  3. 任务封装
  4. 把任务放入线程池
  5. 执行任务
  6. 把要回应的数据放入回复列表CProxyConn::SendResponsePdulist
  7. epoll所在线程读取回复列表的数据发给请求端

连接池

  1. 为什么使用连接池?
    答:对象复用,减小频繁创建链接释放链接的开销时间。
  2. 为什么分开不同的db redis?
    答:方便扩展。
  3. pool_name的意义?
    答:抽象,不必关注redis是否分布式。

redis连接池

  1. CacheInstances=unread,group_set,token,sync,group_member 5 个连接池

  2. 具体设计逻辑?
    答:设计了redis连接池。具体工作细节简要概括如下:

  3. 第一步我们先创建redis连接池类(CachePool类),该类的私有成员变量主要有存放redis的连接list容器;每个redis连接池的对象的名字(m_pool_name);该类的方法主要有获取和释放redis连接,获取连接池的对象的名字等。

  4. 第二步我们创建CacheManager类用来管理redis连接池对象。该类的私有成员变量主要有map容器在将连接池对象的pool_name和连接池对象映射起来。db_proxy_server的main函数首先初始化CacheManager类的单例对象(pCacheManager)。主要逻辑是读取配置文件来创建不同的redis连接池,不同的连接池有不同的名字,创建连接池对象后,放到一个map容器里管理起来。连接池主要包括(unread group_member等)我们后续的相关业务逻辑主要实现了unread 连接池,里面包括主要包括单聊和群聊的未读消息计数。

  5. unread的业务逻辑展开:数据库代理模块之redis

MySQL连接池

答:设计了MySQL连接池。

  1. 第一步我们先创建MySQL连接池类(CDBPool类),该类的私有成员变量主要有存放MySQL的连接list容器;每个MySQL连接池的对象的名字(m_pool_name);
  2. 第二步我们创建CDBManager类用来管理MySQL连接池对象。该类的私有成员变量主要用map容器将MySQL连接池对象的名字pool_name和MySQL连接池对象映射起来。在db_proxy_server的main函数初始化CDBManager类的单例对象。主要逻辑是读取配置文件来创建不同的MySQL连接池(主库master和从库slave),创建连接池对象后,insert map容器里管理起来。
    线程池
    设计初衷:db_proxy_server的主线程(IO线程)用来进行网络IO(收发数据包以及解包逻辑,耗时的查询数据库等操作会包装成task对象,投递到工作线程池里,由线程池的工作线程进行处理)。
    具体实现:
    CWorkerThread类私有成员变量包含互斥锁,条件变量,线程idx,list<CTask*> m_task_list;对外提供接口有start()用于启动一个线程;Execute()执行任务task。
void CWorkerThread::Execute()
{
    while (true) {
        m_thread_notify.Lock();

        // put wait in while cause there can be spurious wake up (due to signal/ENITR)
        while (m_task_list.empty()) {
            m_thread_notify.Wait();
        }

        CTask* pTask = m_task_list.front();
        m_task_list.pop_front();
        m_thread_notify.Unlock();

        pTask->run();

        delete pTask;

        m_task_cnt++;
        //log("%d have the execute %d task\n", m_thread_idx, m_task_cnt);
    }
}

我们使用的是CThreadPool类对象,CThreadPool类私有成员变量包含线程个数以及工作线程数组。对外接口提供初始化(根据入参工作线程个数动态创建工作线程数组)和销毁工作线程数组操作;接收task(往工作线程池里投递任务task),现在是随机选取一个工作线程的idx来进行投递,其实更好的应该是做负载均衡。

void CThreadPool::AddTask(CTask* pTask)
{
        /*
         * select a random thread to push task
         * we can also select a thread that has less task to do
         * but that will scan the whole thread list and use thread lock to get each task size
         */
        uint32_t thread_idx = random() % m_worker_size;
        m_worker_list[thread_idx].PushTask(pTask);
}

void CWorkerThread::PushTask(CTask* pTask)
{
        m_thread_notify.Lock();
        m_task_list.push_back(pTask);
        m_thread_notify.Signal();
        m_thread_notify.Unlock();
}

单聊消息

消息如何封装?如何保证对端完整解析一帧消息?协议格式?

  1. 答:消息封装采用包头(Header)+包体(Body)的格式。包头自定义格式如下代码所示,包体采用protobuf序列化。
typedef struct {
    uint32_t    length;        // the whole pdu length
    uint16_t    version;       // pdu version number
    uint16_t    flag;          // not used
    uint16_t    service_id;    //
    uint16_t    command_id;    //
    uint16_t    seq_num;       // 包序号
    uint16_t    reversed;      // 保留
} PduHeader_t;
  1. 如何保证对端完整解析一帧消息?
  • 采用tcp保证数据传输可靠性
  • 通过包头的 length 字段标记一帧消息的长度
  • 通过service id 和 command id区分不同的命令(比如登录、退出等)
  • 解决数据TCP粘包(包头长度字段)、半包(放入网络库的缓冲区)问题
void CImConn::OnRead()
{
    for (;;)
    {
                uint32_t free_buf_len = m_in_buf.GetAllocSize() - m_in_buf.GetWriteOffset();
                if (free_buf_len < READ_BUF_SIZE)
                        m_in_buf.Extend(READ_BUF_SIZE);

                int ret = netlib_recv(m_handle, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);
                if (ret <= 0)
                        break;

                m_recv_bytes += ret;
                m_in_buf.IncWriteOffset(ret);

                m_last_recv_tick = get_tick_count();
        }

    CImPdu* pPdu = NULL;
        try
    {
                while ( ( pPdu = CImPdu::ReadPdu(m_in_buf.GetBuffer(), m_in_buf.GetWriteOffset()) ) )
                {
            uint32_t pdu_len = pPdu->GetLength();
            
                        HandlePdu(pPdu);

                        m_in_buf.Read(NULL, pdu_len);
                        delete pPdu;
            pPdu = NULL;
//                        ++g_recv_pkt_cnt;
                }
        } catch (CPduException& ex) {
                log("!!!catch exception, sid=%u, cid=%u, err_code=%u, err_msg=%s, close the connection ",
                                ex.GetServiceId(), ex.GetCommandId(), ex.GetErrorCode(), ex.GetErrorMsg());
        if (pPdu) {
            delete pPdu;
            pPdu = NULL;
        }
        OnClose();
        }
}
  1. 协议格式
message IMMsgData{
        //cmd id:                0x0301
        required uint32 from_user_id = 1;    //消息发送方
        required uint32 to_session_id = 2;    //消息接受方
        required uint32 msg_id = 3;
        required uint32 create_time = 4; 
        required IM.BaseDefine.MsgType msg_type = 5;
        required bytes msg_data = 6;
        optional bytes attach_data = 20;
}

message IMMsgDataAck{
        //cmd id:                0x0302
        required uint32 user_id = 1;    //发送此信令的用户id
        required uint32 session_id = 2;                                
        required uint32 msg_id = 3;
        required IM.BaseDefine.SessionType session_type = 4;
}

单聊消息流转流程

db_proxy_server示意图:
在这里插入图片描述

答:两个用户A给B发消息,用户A把聊天消息封装好以后发送给MsgServer;同时把消息进行持久化,将聊天消息发给这个 DBProxy(数据库代理服务),存储消息成功后,DBProxyServer组包应答MsgServer,MsgServer收到回复后组包应答Client A。如果 A 和 B 两个用户不在同一个 MsgServer 上,那么会通过这个 RouteServer 去中转Pdu包数据(广播给所有的MsgServer,MsgServer再广播给Client B),B收到消息后应答MsgServer,至此,流程结束。然后如果是一些热点数据(未读消息计数;msg_id计数),我们同时也会写Redis。

消息序号(msg_id )为什么使用redis生成?

  1. 消息ID(msg_id )的作用是防止消息乱序。
  2. 消息ID(msg_id )为什么这么设计?
    答:msg_id 存储在 unread 连接池所在的redis数据库。单聊 msg_id 的 key涉及到 nRelateId。nRelateId 从关系表(IMRelationShip :两个用户id的映射关系)中获取。
/**
 *  获取会话关系ID
 *  对于群组,必须把nUserBId设置为群ID
 *
 *  @param nUserAId  <#nUserAId description#>
 *  @param nUserBId  <#nUserBId description#>
 *  @param bAdd      <#bAdd description#>
 *  @param nStatus 0 获取未被删除会话,1获取所有。
 */
uint32_t CRelationModel::getRelationId(uint32_t nUserAId, uint32_t nUserBId, bool bAdd)
{
    uint32_t nRelationId = INVALID_VALUE;
    if (nUserAId == 0 || nUserBId == 0) {
        log("invalied user id:%u->%u", nUserAId, nUserBId);
        return nRelationId;
    }
    CDBManager* pDBManager = CDBManager::getInstance();
    CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave");
    if (pDBConn)
    {
        uint32_t nBigId = nUserAId > nUserBId ? nUserAId : nUserBId;
        uint32_t nSmallId = nUserAId > nUserBId ? nUserBId : nUserAId;
        string strSql = "select id from IMRelationShip where smallId=" + int2string(nSmallId) + " and bigId="+ int2string(nBigId) + " and status = 0";
        
        CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str());
        if (pResultSet)
        {
            while (pResultSet->Next())
            {
                nRelationId = pResultSet->GetInt("id");
            }
            delete pResultSet;
        }
        else
        {
            log("there is no result for sql:%s", strSql.c_str());
        }
        pDBManager->RelDBConn(pDBConn);
        if (nRelationId == INVALID_VALUE && bAdd)
        {
            nRelationId = addRelation(nSmallId, nBigId);
        }
    }
    else
    {
        log("no db connection for teamtalk_slave");
    }
    return nRelationId;
}
3. 群聊和单聊msg_id 的区别:key设置不同。
uint32_t CMessageModel::getMsgId(uint32_t nRelateId)
{
    uint32_t nMsgId = 0;
    CacheManager* pCacheManager = CacheManager::getInstance();
    CacheConn* pCacheConn = pCacheManager->GetCacheConn("unread");
    if(pCacheConn)
    {
        string strKey = "msg_id_" + int2string(nRelateId);
        nMsgId = pCacheConn->incrBy(strKey, 1);
        pCacheManager->RelCacheConn(pCacheConn);
    }
    return nMsgId;
}

/**
 *  获取一个群组的msgId,自增,通过redis控制
 *  @param nGroupId 群Id
 *  @return 返回msgId
 */
uint32_t CGroupMessageModel::getMsgId(uint32_t nGroupId)
{
    uint32_t nMsgId = 0;
    CacheManager* pCacheManager = CacheManager::getInstance();
    CacheConn* pCacheConn = pCacheManager->GetCacheConn("unread");
    if(pCacheConn)
    {
        // TODO
        string strKey = "group_msg_id_" + int2string(nGroupId);
        nMsgId = pCacheConn->incrBy(strKey, 1);
        pCacheManager->RelCacheConn(pCacheConn);
    }
    else
    {
        log("no cache connection for unread");
    }
    return nMsgId;
}

未读消息计数

未读消息计数

  • 未读消息为什么不可以用MySQL?(提高效率)

未读消息计数之单聊

key设计:“unread_ + int2string(nUserld)”
使用一个hash存储同一个user_id对应不同聊天的未读消息数量
暂时无法在飞书文档外展示此内容
发送消息时,写入数据库后;增加对方未读消息计数调用 incMsgCount 函数接口。

void CMessageModel::incMsgCount(uint32_t nFromId, uint32_t nToId)
{
    CacheManager* pCacheManager = CacheManager::getInstance();
    // increase message count
    CacheConn* pCacheConn = pCacheManager->GetCacheConn("unread");
    if (pCacheConn) {
        pCacheConn->hincrBy("unread_" + int2string(nToId), int2string(nFromId), 1);
        pCacheManager->RelCacheConn(pCacheConn);
    } else {
        log("no cache connection to increase unread count: %d->%d", nFromId, nToId);
    }
}

未读消息计数之群聊

思考:一千人的大群,1个人发信息,其他人都不在线,给每个群成员做未读计数吗?
群聊的未读消息机制如果和单聊做同样的设计?即收到群聊后对每个群成员聊天数量+1?答:效率低下。
方案如下:

  1. 一个群groud_id对应多个user_id
  2. 同一个groud_id,不同的user_id对应的未读消息数量是不一样的
  3. 每次发消息时群消息数量+1,发消息的个人计数也+1
  4. 未读消息数量:群消息数量 - 个人已读消息数量
    对于群组未读消息,每个人都是不一样的,所以设计如下:
    key为"nGroupld_ + nUserld"结合。
#define GROUP_TOTAL_MSG_COUNTER_REDIS_KEY_SUFFIX    "_im_group_msg"
#define GROUP_USER_MSG_COUNTER_REDIS_KEY_SUFFIX     "_im_user_group"
#define GROUP_COUNTER_SUBKEY_COUNTER_FIELD          "count"

作为消息发送者,首先增加群消息总共的消息数量,同时在发送群聊的时候也要把自己的消息计数设置成和群消息数量一样(即没有未读计数)。

/**
 *  增加群消息计数
 *
 *  @param nUserId  用户Id
 *  @param nGroupId 群组Id
 *
 *  @return 成功返回true,失败返回false
 */
bool CGroupMessageModel::incMessageCount(uint32_t nUserId, uint32_t nGroupId)
{
    bool bRet = false;
    CacheManager* pCacheManager = CacheManager::getInstance();
    CacheConn* pCacheConn = pCacheManager->GetCacheConn("unread");
    if (pCacheConn)
    {
        string strGroupKey = int2string(nGroupId) + GROUP_TOTAL_MSG_COUNTER_REDIS_KEY_SUFFIX;
        pCacheConn->hincrBy(strGroupKey, GROUP_COUNTER_SUBKEY_COUNTER_FIELD, 1);
        map<string, string> mapGroupCount;
        bool bRet = pCacheConn->hgetAll(strGroupKey, mapGroupCount);
        if(bRet)
        {
            string strUserKey = int2string(nUserId) + "_" + int2string(nGroupId) + GROUP_USER_MSG_COUNTER_REDIS_KEY_SUFFIX;
            string strReply = pCacheConn->hmset(strUserKey, mapGroupCount);
            if(!strReply.empty())
            {
                bRet = true;
            }
            else
            {
                log("hmset %s failed !", strUserKey.c_str());
            }
        }
        else
        {
            log("hgetAll %s failed!", strGroupKey.c_str());
        }
        pCacheManager->RelCacheConn(pCacheConn);
    }
    else
    {
        log("no cache connection for unread");
    }
    return bRet;
}

清除未读消息计数

CID_MSG_READ_ACK 代表我们已经阅读了消息
CID_MSG_DATA ACK 代表收到消息
单聊和群聊:
客户端读取消息后要发送CID_MSG_READ_ACK给服务器,服务器根据该命令清除未读消息计数。

  • 单聊:直接删除"unread_nUserId" 的key
  • 群聊:更新 “user_id+group_id+_im_user_group”(自己已经读取的消息数量) 对应的value和"group_id+_im_group_msg"(群总共的消息数量)一致
m_handler_map.insert(make_pair(
    uint32_t(CID_MSG_READ_ACK), DB_PROXY::clearUnreadMsgCounter));
    
    void clearUnreadMsgCounter(CImPdu* pPdu, uint32_t conn_uuid)
    {
        IM::Message::IMMsgDataReadAck msg;
        if(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
        {
            uint32_t nUserId = msg.user_id();
            uint32_t nFromId = msg.session_id();
            IM::BaseDefine::SessionType nSessionType = msg.session_type();
            CUserModel::getInstance()->clearUserCounter(nUserId, nFromId, nSessionType);
            log("userId=%u, peerId=%u, type=%u", nFromId, nUserId, nSessionType);
        }
        else
        {
            log("parse pb failed");
        }
    }
void CUserModel::clearUserCounter(uint32_t nUserId, uint32_t nPeerId, IM::BaseDefine::SessionType nSessionType)
{
    if(IM::BaseDefine::SessionType_IsValid(nSessionType))
    {
        CacheManager* pCacheManager = CacheManager::getInstance();
        CacheConn* pCacheConn = pCacheManager->GetCacheConn("unread");
        if (pCacheConn)
        {
            // Clear P2P msg Counter
            if(nSessionType == IM::BaseDefine::SESSION_TYPE_SINGLE)
            {
                int nRet = pCacheConn->hdel("unread_" + int2string(nUserId), int2string(nPeerId));
                if(!nRet)
                {
                    log("hdel failed %d->%d", nPeerId, nUserId);
                }
            }
            // Clear Group msg Counter
            else if(nSessionType == IM::BaseDefine::SESSION_TYPE_GROUP)
            {
                string strGroupKey = int2string(nPeerId) + GROUP_TOTAL_MSG_COUNTER_REDIS_KEY_SUFFIX;
                map<string, string> mapGroupCount;
                bool bRet = pCacheConn->hgetAll(strGroupKey, mapGroupCount);
                if(bRet)
                {
                    string strUserKey = int2string(nUserId) + "_" + int2string(nPeerId) + GROUP_USER_MSG_COUNTER_REDIS_KEY_SUFFIX;
                    string strReply = pCacheConn->hmset(strUserKey, mapGroupCount);
                    if(strReply.empty()) {
                        log("hmset %s failed !", strUserKey.c_str());
                    }
                }
                else
                {
                    log("hgetall %s failed!", strGroupKey.c_str());
                }
                
            }
            pCacheManager->RelCacheConn(pCacheConn);
        }
        else
        {
            log("no cache connection for unread");
        }
    }
    else{
        log("invalid sessionType. userId=%u, fromId=%u, sessionType=%u", nUserId, nPeerId, nSessionType);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值