Python下Mysql數據連接池——單例
阿新 • • 發佈:2018-01-12
get passwd ati odi xca asa axshare it is created
# coding:utf-8 import threading import pymysql from DBUtils.PooledDB import PooledDB from app.common.file_config import get_config class DbPool(object): _instance_lock = threading.Lock() def __init__(self): if not hasattr(DbPool, "pool"): DbPool.mysql_pool()else: pass def __new__(cls, *args, **kwargs): if not hasattr(DbPool, "_instance"): with DbPool._instance_lock: if not hasattr(DbPool, "_instance"): DbPool._instance = object.__new__(cls, *args, **kwargs) return DbPool._instance @staticmethoddef mysql_pool(): host = get_config(‘database‘, ‘MYSQL_HOST‘) port = int(get_config(‘database‘, ‘MYSQL_PORT‘)) user = get_config(‘database‘, ‘MYSQL_USERNAME‘) passwd = get_config(‘database‘, ‘MYSQL_PASSWORD‘) db = get_config(‘database‘, ‘MYSQL_DB‘) DbPool.pool= PooledDB( creator=pymysql, # 使用鏈接數據庫的模塊 mincached=2, # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建 maxcached=6, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。 maxconnections=8, # 連接池允許的最大連接數,0和None表示不限制連接數 blocking=True, # 連接池中如果沒有可用連接後,是否阻塞等待。True,等待;False,不等待然後報錯 maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制 setsession=None, # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host=host, port=port, user=user, passwd=passwd, db=db, use_unicode=False, charset=‘utf8‘ )
Python下Mysql數據連接池——單例