python使用多執行緒備份資料庫

Lucky_Tomato發表於2021-05-29

前言:在日常伺服器運維工作中,備份資料庫是必不可少的,剛工作那會看到公司都是用shell指令碼迴圈備份資料庫,到現在自己學習python語言後,利用多程式多執行緒相關技術來實現並行備份資料庫,充分利用伺服器資源,提高備份速度。

 

一、為什麼要用執行緒池

1.多執行緒比單執行緒執行要快很多,比如在我工作中,每臺伺服器至少8個庫以上,用單執行緒備份太慢了。

2.不是越多執行緒就會越好,而是根據伺服器的資源來合理定義worker執行緒,否則會造成伺服器嚴重負載,影響到線上業務。

3.備份資料庫都是消耗IO操作,用多執行緒比多程式稍微會更有優勢。

從Python3.2開始,標準庫為我們提供了 concurrent.futures 模組,它提供了 ThreadPoolExecutor (執行緒池)和ProcessPoolExecutor (程式池)兩個類。
相比 threading 等模組,該模組通過 submit 返回的是一個 future 物件,它是一個未來可期的物件,通過它可以獲悉執行緒的狀態主執行緒(或程式)中可以獲取某一個執行緒(程式)執行的狀態或者某一個任務執行的狀態及返回值:
主執行緒可以獲取某一個執行緒(或者任務的)的狀態,以及返回值。
當一個執行緒完成的時候,主執行緒能夠立即知道。
讓多執行緒和多程式的編碼介面一致。
 
二、執行緒池練習
演示例子1:使用submit方法
from concurrent.futures import ThreadPoolExecutor
import time

def test_thread(sec):
    time.sleep(sec)
    print(f"sleep {sec} done")
    return sec

with ThreadPoolExecutor(max_workers=4) as t:  # 建立一個最大容納數量為4的執行緒池
    task1 = t.submit(test_thread, 1)
    task2 = t.submit(test_thread, 2)  # 通過submit提交執行的函式到執行緒池中
    task3 = t.submit(test_thread, 3)

    print(f"task1: {task1.done()}")  # 通過done來判斷執行緒是否完成
    print(f"task2: {task2.done()}")
    print(f"task3: {task3.done()}")

    time.sleep(2.5)
    print(f"task1: {task1.done()}")
    print(f"task2: {task2.done()}")
    print(f"task3: {task3.done()}")
    print(task1.result())  # 通過result來獲取返回值

結果輸出:

task1: False
task2: False
task3: False
sleep 1 done
sleep 2 done
task1: True
task2: True
task3: False
1
sleep 3 done
使用 with 語句 ,通過 ThreadPoolExecutor 構造例項,同時傳入 max_workers 引數來設定執行緒池中最多能同時執行的執行緒數目。
使用 submit 函式來提交執行緒需要執行的任務到執行緒池中,並返回該任務的控制程式碼(類似於檔案、畫圖),注意 submit() 不是阻塞的,而是立即返回。
通過使用 done() 方法判斷該任務是否結束。上面的例子可以看出,提交任務後立即判斷任務狀態,顯示3個任務都未完成。在延時2.5後,task1 和 task2 執行完畢,task3 仍在執行中。
 
演示例子2:使用map方法
import time
from concurrent.futures import ThreadPoolExecutor

def spider(page):
    time.sleep(page)
    return page

start = time.time()
executor = ThreadPoolExecutor(max_workers=4)

i = 1
for result in executor.map(spider, [2, 3, 1, 4]):
    print("task{}:{}".format(i, result))
    i += 1

結果輸出:

task1:2
task2:3
task3:1
task4:4
from concurrent.futures import ThreadPoolExecutor有兩種方式,一種是submit()函式,另一種是map()函式,兩者的主要區別在於:
1.map可以保證輸出的順序, submit輸出的順序是亂的
2.如果你要提交的任務的函式是一樣的,就可以簡化成map。但是假如提交的任務函式是不一樣的,或者執行的過程之可能出現異常(使用map執行過程中發現問題會直接丟擲錯誤)就要用到submit()
3.submit和map的引數是不同的,submit每次都需要提交一個目標函式和對應的引數,map只需要提交一次目標函式,目標函式的引數放在一個迭代器(列表,字典)裡就可以。

三、線上資料庫測試

環境:centos6,資料庫版本5.7,資料備份2個1.7G、一個800M、一個200M

第一種:shell指令碼for的方式備份4個資料庫

#!/bin/bash
backup_path="/data/backup/"
myuser="root"
mypwd="123456"
db_name="test_1000"
current_time=$(date +%Y%m%d%H%M%S)
for i in $(seq 4);do
    /usr/local/mysql/bin/mysqldump -u${myuser} -p${mypwd} --single-transaction --master-data=2 --set-gtid-purged=off "${db_name}${i}" | gzip > ${backup_path}/"${db_name}${i}"_${current_t
ime}.sql.gz
done

檢視執行時間    

mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.

real    4m28.421s
user    3m50.360s
sys     0m5.962s

第二種方式:多執行緒備份  

  

可以明顯看到優勢

 

總結:在伺服器上有需要備份多個資料庫時,使用python多執行緒的方式比傳統的shell指令碼迴圈備份會更有優勢,可以充分利用伺服器上的資源,有效提升效率。

  

詳細參考:

  

  

  

 
 

相關文章