常規的數據庫鏈接存在的問題:
場景一:
缺點:每次請求反復創建數據庫連接,連接數太多
import pymysql def index(): conn = pymysql.connect() cursor = conn.cursor() cursor.execute('select * from tb where id > %s',[5,]) result = cursor.fetchall() cursor.close() conn.close() print(result) def update(): # 第一步:缺點:每次請求反復創建數據庫連接,連接數太多 conn = pymysql.connect() cursor = conn.cursor() cursor.execute('update userinfo set username=%s where id > %s',['ctz',5,]) conn.commit() cursor.close() conn.close() return 'hello'
存在問題:每一次請求就得創建數據庫鏈接,可能我們處理數據只需要很少時間,而連接數據庫卻占了很長時間,每次請求反復創建數據庫連接,連接數太多,造成數據庫性能的損耗
場景二:
缺點,不能支持並發
import pymysql CONN=pymysql.connect() def index(): cursor = CONN.cursor() cursor.execute('select * from tb where id > %s',[5,]) result = cursor.fetchall() cursor.close() CONN.close() print(result) def update(): cursor = CONN.cursor() cursor.execute('update userinfo set username=%s where id > %s',['ctz',5,]) CONN.commit() cursor.close() CONN.close() return 'hello'
把數據庫鏈接放到常量中去了,這樣就可以保證每次請求都只創建一次數據庫鏈接,但是還是存在問題:不能支持並發
如果有多個線程進來的話要執行同一個函數,第一個線程還沒執行玩,第二個線程進來啦,但是只有一個conn這時就報錯;當然我們也可以用下面這種方式解決報錯問題:
import threading LOCK=threading.RLock() CONN=pymysql.connect() def index(): with LOCK: cursor = CONN.cursor() cursor.execute('select * from tb where id > %s', [5, ]) result = cursor.fetchall() cursor.close() print(result)
但是 這樣雖然解決了多個線程競爭報錯的問題,但是程序加鎖后變成了串行,運行效率就變低了
為了解決上面兩個場景出現的問題,我們找到了解決的辦法,就是創建數據庫連接池
數據庫鏈接池
DBUtils是Python的一個用於實現數據庫連接池的模塊。
此連接池有兩種連接模式:
- 模式一:為每個線程創建一個連接,線程即使調用了close方法,也不會關閉,只是把連接重新放到連接池,供自己線程再次使用。當線程終止時,連接自動關閉。
實現原理:基於threaing.local實現為每一個線程創建一個鏈接,該線程關閉時,不是真正關閉;本線程再次調用時,還是使用的最開始創建的連接。直到線程終止,數據庫連接才關閉
""" 為每個線程創建一個連接,thread.local實現。 """ from DBUtils.PersistentDB import PersistentDB import pymysql POOL = PersistentDB( creator=pymysql, # 使用鏈接數據庫的模塊 maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制 setsession=[], # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # 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 closeable=False, # 如果為False時, conn.close() 實際上被忽略,供下次使用,再線程關閉時,才會自動關閉鏈接。如果為True時, conn.close()則關閉鏈接,那么再次調用pool.connection時就會報錯,因為已經真的關閉了連接(pool.steady_connection()可以獲取一個新的鏈接) threadlocal=None, # 本線程獨享值得對象,用於保存鏈接對象,如果鏈接對象被重置 host='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) def func(): # conn = SteadyDBConnection() conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() cursor.close() conn.close() # 不是真的關閉,而是假的關閉。 conn = pymysql.connect() conn.close() conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() cursor.close() conn.close() import threading for i in range(10): t = threading.Thread(target=func) t.start()
模式二:創建一批連接到連接池,供所有線程共享使用,使用時來進行獲取,使用完畢后,再次放回到連接池。
PS:由於pymysql、MySQLdb等threadsafety值為1,所以該模式連接池中的線程會被所有線程共享。
import time import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用鏈接數據庫的模塊 maxconnections=6, # 連接池允許的最大連接數,0和None表示不限制連接數 mincached=2, # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建 maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。 blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯 maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制 setsession=[], # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # 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='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) def func(): # 檢測當前正在運行連接數的是否小於最大鏈接數,如果不小於則:等待或報raise TooManyConnections異常 # 否則 # 則優先去初始化時創建的鏈接中獲取鏈接 SteadyDBConnection。 # 然后將SteadyDBConnection對象封裝到PooledDedicatedDBConnection中並返回。 # 如果最開始創建的鏈接沒有鏈接,則去創建一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中並返回。 # 一旦關閉鏈接后,連接就返回到連接池讓后續線程繼續使用。 # PooledDedicatedDBConnection conn = POOL.connection() # print(th, '鏈接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() conn = POOL.connection() # print(th, '鏈接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() func()
PS:
如果有三個線程來連接池中獲取鏈接: 1個鏈接可以為三個線程提供服務 2個鏈接可以為三個線程提供服務 3個鏈接可以為三個線程提供服務 maxshared在使用pymysql/mysqldb時均無用,因為他們的threadsafety都是1,而查看PooledDB源碼就可以知道 if threadsafety > 1 and maxshared: self._maxshared = maxshared self._shared_cache = [] # the cache for shared connections else: self._maxshared = 0 即使設置了 永遠都是0