天天看點

Flask之資料庫連接配接池——DBUtils子產品

DBUtils

  • DBUtils是Python的一個用于實作資料庫連接配接池的子產品。
  • 此連接配接池有兩種連接配接模式:

一、獨立線程

  • 模式一:為每個線程建立一個連接配接。線程即使調用了close方法,也不會關閉,隻是把連接配接重新放到連接配接池,供自己線程再次使用。當線程終止時,才會将連接配接自動關閉。
  • 但這種方法:一方面可能線程數特别多。不可控,需要控制線程 ;另一方面,每個線程要運作結束才能自動關閉,占有資源。
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 (一般情況下,使用4就可以)
    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 = POOL.connection(shareable=False)
    # 拿到一個光标
    cursor = conn.cursor()
    # 執行SQL語句
    cursor.execute('select * from tb1')
    # 執行
    result = cursor.fetchall()
    # 關閉執行
    cursor.close()
    # 關閉連接配接
    conn.close()

func()
           

二、線程共享連接配接池:<惰性建立>(推薦)

  • 模式二:建立一批連接配接到連接配接池,供所有線程共享使用
  • 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中并傳回。
    # 一旦關閉連結後,連接配接就傳回到連接配接池讓後續線程繼續使用。
    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()
           

三、線程加鎖

  • 如果沒有連接配接池,使用pymysql來連接配接資料庫時,單線程應用完全沒有問題,但如果涉及到多線程應用那麼就需要加鎖。但是,一旦加鎖那麼連接配接勢必就會排隊等待,當請求比較多時,性能就會降低了。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
import threading
CONN = pymysql.connect(host='127.0.0.1',
                       port=3306,
                       user='root',
                       password='123',
                       database='pooldb',
                       charset='utf8')


def task(arg):
    cursor = CONN.cursor()
    cursor.execute('select * from tb1')
    result = cursor.fetchall()
    cursor.close()

    print(result)


for i in range(10):
    t = threading.Thread(target=task, args=(i,))
    t.start()

無鎖(報錯)