数据库的增删改查都先要链接数据库,不然到处都在链接数据库,很烂费资源和性能,今天就把mongo的连接池的单例模式封装了一下,希望大家多多指教:
# -*- coding: utf-8 -*-
"""
@Time : 2020/11/23 16:36
@Athor : LinXiao
@功能 :
"""
import os
import sys
from pymongo import MongoClient
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
class MongoDBClient(object):
# 饿汉式 单例模式
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance=super(MongoDBClient, cls).__new__(cls)
return cls.instance
# 代理ip Redis 连接池
def __init__(self):
# uri='mongodb://账号:密码@128.777.244.19:27017/admin'
# self.mgdb=MongoClient(uri, connect=False, maxPoolSize=2000)
local_host='localhost'
local_port=27017
self.local_client=MongoClient(local_host, local_port, connect=False, maxPoolSize=2000)
# 线上mongo验证
online_host="145455.12.122线上mongo地址"
online_port=27017
client=MongoClient(online_host, online_port,connect=False, maxPoolSize=2000)
db_user='dbwd'
password='fpy#线上mongo密码'
db=client.test # 注意:# 先连接系统默认数据库admin
db.authenticate(db_user, password, mechanism='SCRAM-SHA-1')
self.online_client=client
def getMongo_Local_Client(self):
return self.local_client
def getMongo_Online_Client(self):
return self.online_client
# if __name__ == '__main__':
# mongo=MongoDBClient().getMongo_Online_Client()
# mongo_insert=mongo['test']["test111111"]
# data={"linxiao": "handsome"}
# mongo_insert.insert_one(data)
#
# 类方法继承
class AA(MongoDBClient):
def __init__(self):
super().__init__()
# def get_data(self):
if __name__ == '__main__':
a1=AA()
a2=AA()
print(id(a1), id(a2))
运行结果:
说明是同一个对象,单利完成!
网友评论