rabbitMq------连接管理模块

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

我们的网络通信框架使用的muduo库,而在mudu库中是已经有了连接的概念,但是我们呢还有一个信道的概念muduo库是没有的。其实muduo库是有一个channel的概念的,只不过这个概念和我们这里的channel不一样。

这也就是我们要封装这个模块的意义。


管理的字段

有一个信道内存管理句柄,因为一个连接上可以有多个信道。

cpp 复制代码
 class Connection
    {
    private:
        muduo::net::TcpConnectionPtr _conn;
        ProtobufCodecPtr _codec;
        VirtualHost::ptr _host;
        ConsumerManager::ptr _cmp;
        ThreadPool::ptr _pool;
        ChannelManager::ptr _channels;
  }

提供了三个操作分别是的打开信道,关闭信道和获取指定信道。

就是调用信道内存管理句柄进行操作。

打开信道和关闭都是需要给客户端返回响应的。

cpp 复制代码
 void openChannel(const openChannelRequestPtr &req){
            bool ret = _channels->openChannel(req->cid(),_host,_cmp,_codec,_conn,_pool);
    if(ret == false)
    {
        return basicResponse(false,req->rid(),req->cid());
    }
    return basicResponse(true,req->rid(),req->cid());
}


void closeChannel(const closeChannelRequestPtr &req){
    _channels->closeChannel(req->cid());
    return basicResponse(true, req->rid(), req->cid());
}

Channel::ptr getChannel(const std::string &cid){
    return _channels->getChannel(cid);
}

连接内存管理对象

服务器上可能会存在多条链接,因此我们也需要把连接管理起来

通过一个哈希表,建立tcp连接和连接管理对象的映射。

cpp 复制代码
class ConnectionManager
    {
    private:
        std::mutex _mutex;
        std::unordered_map<muduo::net::TcpConnectionPtr,Connection::ptr> _conns;
   }

提供三个操作,新建连接。关闭连接和获取指定连接。

在服务器中就需要管理这个句柄,就可以管理所有的channel了。

cpp 复制代码
void newConnection(const VirtualHost::ptr &host,
                    const ConsumerManager::ptr &cmp,
                    const ProtobufCodecPtr &codec,
                    const muduo::net::TcpConnectionPtr &conn,
                    const ThreadPool::ptr &pool){
     std::unique_lock<std::mutex> lock(_mutex);
     auto it = _conns.find(conn);
     if (it != _conns.end()) {
         return ;
     }
     Connection::ptr self_conn = std::make_shared<Connection>(host,cmp, codec, conn, pool);
     _conns.insert(std::make_pair(conn, self_conn));   
 }


 void delConnection(const muduo::net::TcpConnectionPtr &conn){
     std::unique_lock<std::mutex> lock(_mutex);
     _conns.erase(conn);
 }



 Connection::ptr getConnection(const muduo::net::TcpConnectionPtr &conn){
     std::unique_lock<std::mutex> lock(_mutex);
     auto it = _conns.find(conn);
     if (it == _conns.end()) {
         return Connection::ptr();
     }
     return it->second;
 }
相关推荐
Thomas.Sir3 天前
第21课:PyTorch|GPU多卡训练与分布式训练基础【让多卡并行成为你的加速引擎】
人工智能·pytorch·分布式
Cicada1283 天前
库存消息消费的正确性设计——从幂等窗口到批量流水线
分布式·系统架构
Francek Chen4 天前
【大数据处理与分析】数据仓库Hive:04 数据仓库Hive概述
大数据·数据仓库·hive·hadoop·分布式
Gl�ria4 天前
Hadoop/YARN 集群缩容:下线DN节点
大数据·hadoop·分布式
吉甫作诵4 天前
Kafka 集群安装与运维实战:消费组排查、Offset 重置与副本重分配
大数据·运维·分布式·kafka·消息队列
imDwAaY4 天前
消息队列四大核心问题:顺序性、幂等性、可靠性与一致性
学习·kafka·rabbitmq
是Dream呀5 天前
Harness 工程:让 Agent 真正把任务做完
人工智能·分布式·缓存·agent
yt004yt5 天前
绿岛数字化平台搭建:VOCs 监测与能碳数据一体化方案
大数据·分布式
天天喝旺仔5 天前
分布式服务容错实战:用 Sentinel 实现限流、熔断与降级
分布式·微服务·云原生·sentinel