溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python使用多線程查詢數(shù)據(jù)庫的案例分析

發(fā)布時間:2020-08-19 10:56:27 來源:億速云 閱讀:262 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)python使用多線程查詢數(shù)據(jù)庫的案例分析的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

一.背景:

         當(dāng)數(shù)據(jù)量過大時,一個程序的執(zhí)行時間就會主要花費在等待單次查詢返回結(jié)果,在這個過程中cpu無疑是處于等待io的空閑狀態(tài)的,這樣既浪費了cpu資源,又花費了大量時間(當(dāng)然這里主要說多線程,批量查詢不在考慮范圍,總會存在不能批量查詢的情況),在這種非密集型運算(及大量占用cpu資源)的情況下在python中無疑運用多線程是一個非常棒的選擇。

二.知識點:

        數(shù)據(jù)庫連接池的運用及優(yōu)勢,python中多線程的運用,隊列的運用

        數(shù)據(jù)庫連接池:限制了數(shù)據(jù)庫的連接最大個數(shù),每次連接都是可以重復(fù)使用的,當(dāng)然也可以限制每個連接的重復(fù)使用次數(shù)(這個在這里是沒必要的),需要注意的是設(shè)置的數(shù)據(jù)庫的最大連接個數(shù)最好要大于我們自己開的最大線程個數(shù),一般邏輯是每個線程占用一個數(shù)據(jù)庫連接可以使程序達(dá)到最大速度,如果小于則可能存在同時連接個數(shù)大于數(shù)據(jù)庫允許的最大連接個數(shù)的風(fēng)險。使用數(shù)據(jù)庫連接池的優(yōu)勢在于,python多線程并發(fā)操作數(shù)據(jù)庫,會存在鏈接數(shù)據(jù)庫超時、數(shù)據(jù)庫連接丟失、數(shù)據(jù)庫操作超時等問題,而數(shù)據(jù)庫連接池提供線程間可共享的數(shù)據(jù)庫連接,并自動管理連接。

       python多線程:在程序等待io的時間里調(diào)用多線程去數(shù)據(jù)庫執(zhí)行查詢操作。

       隊列:這個就是數(shù)據(jù)結(jié)構(gòu)里面的知識了,一般隊列的常用模式先進先出隊列。(這里主要用的是隊列取一個數(shù)就少一個數(shù)的原理,其實用列表也可以實現(xiàn),他的先進先出主要強調(diào)的是一個順序關(guān)系,這一點到?jīng)]用上,就當(dāng)是練練手了)

三.兩段代碼作比較:

數(shù)據(jù)庫的截圖:

python使用多線程查詢數(shù)據(jù)庫的案例分析

第一段代碼:正常循環(huán)查詢并打印出執(zhí)行時間

#!/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 # 最低預(yù)啟動數(shù)據(jù)庫連接數(shù)量
  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,%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)

執(zhí)行結(jié)果:

python使用多線程查詢數(shù)據(jù)庫的案例分析

第二段代碼:限制數(shù)據(jù)庫連接池最大15個連接,用隊列限制最大線程個數(shù)為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 # 最低預(yù)啟動數(shù)據(jù)庫連接數(shù)量
  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

def tread_connection_db(id):
  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,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight']))
  else:
    print('this tread %s result is none'%id)
  con.close()


if __name__=='__main__':
  start = time.time()
  #創(chuàng)建線程連接池,最大限制15個連接
  pool = mysql_connection()
  #創(chuàng)建隊列,隊列的最大個數(shù)及限制線程個數(shù)
  q=Queue.Queue(maxsize=10)
  #測試數(shù)據(jù),多線程查詢數(shù)據(jù)庫
  for id in range(50):
    #創(chuàng)建線程并放入隊列中
    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)

程序備注應(yīng)該還算比較清晰的哈,程序執(zhí)行結(jié)果:

python使用多線程查詢數(shù)據(jù)庫的案例分析

感謝各位的閱讀!關(guān)于python使用多線程查詢數(shù)據(jù)庫的案例分析就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI