简体   繁体   English

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

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

The way I connect to Mongo and disconnect:我连接到 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()

And I use with to open and close a connection with Mongo.我使用with打开和关闭与 Mongo 的连接。 I want to track the number of opened connections, every time I open and close a connection.我想在每次打开和关闭连接时跟踪打开的连接数。 Just a simple print will do.只需简单的打印即可。 But how do I get to the field that contains the number of connections?但是我如何到达包含连接数的字段? I looked at dir of self.client but it does not have a special method method for.我查看了self.clientdir ,但它没有特殊的方法方法。 I want to know the number of connections in runtime.我想知道运行时的连接数。 How can I do it?我该怎么做?

One way to approach it could be to add a counter as a class variable which increments and decrements the total number of connections upon calling the open och close methods.一种解决方法是添加一个计数器作为 class 变量,该变量在调用 open och close 方法时增加和减少连接总数。 Something like the below:如下所示:

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