繁体   English   中英

如何在运行时获取打开的 Mongo 连接数?

[英]How to get the number of opened Mongo connections in runtime?

我连接到 Mongo 并断开连接的方式:

class Database:
    def connect(self):
        self.client = MongoClient(self.uri)

    def close(self):
        if self.client:
            self.client.close()


    def __enter__(self):
        if self.is_not_connected():
            self.connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

我使用with打开和关闭与 Mongo 的连接。 我想在每次打开和关闭连接时跟踪打开的连接数。 只需简单的打印即可。 但是我如何到达包含连接数的字段? 我查看了self.clientdir ,但它没有特殊的方法方法。 我想知道运行时的连接数。 我该怎么做?

一种解决方法是添加一个计数器作为 class 变量,该变量在调用 open och close 方法时增加和减少连接总数。 如下所示:

class Database:
    num_of_connections = 0

    def connect(self):
        Database.num_of_connections += 1
        self.client = MongoClient(self.uri)

    def close(self):
        if self.client:
            Database.num_of_connections -= 1
            self.client.close()

    def __enter__(self):
        if self.is_not_connected():
            self.connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def active_connections(self):
        print(Database.num_of_connections)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM