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;
 }
相关推荐
用户83071968408218 小时前
RabbitMQ vs RocketMQ 事务大对决:一个在“裸奔”,一个在“开挂”?
后端·rabbitmq·rocketmq
初次攀爬者2 天前
RabbitMQ的消息模式和高级特性
后端·消息队列·rabbitmq
初次攀爬者4 天前
ZooKeeper 实现分布式锁的两种方式
分布式·后端·zookeeper
让我上个超影吧5 天前
消息队列——RabbitMQ(高级)
java·rabbitmq
塔中妖5 天前
Windows 安装 RabbitMQ 详细教程(含 Erlang 环境配置)
windows·rabbitmq·erlang
断手当码农5 天前
Redis 实现分布式锁的三种方式
数据库·redis·分布式
初次攀爬者5 天前
Redis分布式锁实现的三种方式-基于setnx,lua脚本和Redisson
redis·分布式·后端
业精于勤_荒于稀5 天前
物流订单系统99.99%可用性全链路容灾体系落地操作手册
分布式
Ronin3055 天前
信道管理模块和异步线程模块
开发语言·c++·rabbitmq·异步线程·信道管理
Asher05095 天前
Hadoop核心技术与实战指南
大数据·hadoop·分布式