python使用多執行緒查詢資料庫的實現示例
一.背景:
當資料量過大時,一個程式的執行時間就會主要花費在等待單次查詢返回結果,在這個過程中cpu無疑是處於等待io的空閒狀態的,這樣既浪費了cpu資源,又花費了大量時間(當然這裡主要說多執行緒,批量查詢不在考慮範圍,總會存在不能批量查詢的情況),在這種非密集型運算(及大量佔用cpu資源)的情況下在python中無疑運用多執行緒是一個非常棒的選擇。
二.知識點:
資料庫連線池的運用及優勢,python中多執行緒的運用,佇列的運用
資料庫連線池:限制了資料庫的連線最大個數,每次連線都是可以重複使用的,當然也可以限制每個連線的重複使用次數(這個在這裡是沒必要的),需要注意的是設定的資料庫的最大連線個數最好要大於我們自己開的最大執行緒個數,一般邏輯是每個執行緒佔用一個數據庫連線可以使程式達到最大速度,如果小於則可能存在同時連線個數大於資料庫允許的最大連線個數的風險。使用資料庫連線池的優勢在於,python多執行緒併發操作資料庫,會存在連結資料庫超時、資料庫連線丟失、資料庫操作超時等問題,而資料庫連線池提供執行緒間可共享的資料庫連線,並自動管理連線。
python多執行緒:在程式等待io的時間裡呼叫多執行緒去資料庫執行查詢操作。
佇列:這個就是資料結構裡面的知識了,一般佇列的常用模式先進先出佇列。(這裡主要用的是佇列取一個數就少一個數的原理,其實用列表也可以實現,他的先進先出主要強調的是一個順序關係,這一點到沒用上,就當是練練手了)
三.兩段程式碼作比較:
資料庫的截圖:
第一段程式碼:正常迴圈查詢並打印出執行時間
#!/usr/bin/python # -*- coding=utf-8 -*- import time import threading import MySQLdb import Queue from MySQLdb.cursors import DictCursor from DBUtils.PooledDB import PooledDB def mysql_connection(): host = 'localhost' user = 'root' port = 3306 password = '123456' db = 'test' charset = 'utf8' limit_count = 3 # 最低預啟動資料庫連線數量 pool = PooledDB(MySQLdb,limit_count,maxconnections=15,host=host,user=user,port=port,passwd=password,db=db,charset=charset,use_unicode=True,cursorclass=DictCursor) return pool start = time.time() pool = mysql_connection() for id in range(50): con = pool.connection() cur = con.cursor() sql = '''select id,name,age,weight from test where id = %s '''%id cur.execute(sql) time.sleep(0.5) result = cur.fetchall() if result: print('this is tread %s (%s,%s,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight'])) else: print('this tread %s result is none'%id) end = time.time() - start print(end)
執行結果:
第二段程式碼:限制資料庫連線池最大15個連線,用佇列限制最大執行緒個數為10個
#!/usr/bin/python # -*- coding=utf-8 -*- import time import threading import MySQLdb import Queue from MySQLdb.cursors import DictCursor from DBUtils.PooledDB import PooledDB def mysql_connection(): host = 'localhost' user = 'root' port = 3306 password = '123456' db = 'test' charset = 'utf8' limit_count = 3 # 最低預啟動資料庫連線數量 pool = PooledDB(MySQLdb,cursorclass=DictCursor) return pool def tread_connection_db(id): con = pool.connection() cur = con.cursor() sql = '''select id,result[0]['weight'])) else: print('this tread %s result is none'%id) con.close() if __name__=='__main__': start = time.time() #建立執行緒連線池,最大限制15個連線 pool = mysql_connection() #建立佇列,佇列的最大個數及限制執行緒個數 q=Queue.Queue(maxsize=10) #測試資料,多執行緒查詢資料庫 for id in range(50): #建立執行緒並放入佇列中 t = threading.Thread(target=tread_connection_db,args=(id,)) q.put(t) #佇列隊滿 if q.qsize()==10: #用於記錄執行緒,便於終止執行緒 join_thread = [] #從對列取出執行緒並開始執行緒,直到佇列為空 while q.empty()!=True: t = q.get() join_thread.append(t) t.start() #終止上一次隊滿時裡面的所有執行緒 for t in join_thread: t.join() end = time.time() - start print(end)
程式備註應該還算比較清晰的哈,程式執行結果:
四.結論:
看結果說話
到此這篇關於python使用多執行緒查詢資料庫的實現示例的文章就介紹到這了,更多相關python 多執行緒查詢資料庫內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!