dưới đây là đoạn mẫu code e test để xử lý khi gặp lỗi đó , thì chạy nó ko báo lỗi gì chỉ dừng script khi gặp lỗi đó hoặc thi thoảng nó hiện lỗi segmentation fault (core dumped) , dừng ở dòng 81
import sys
from time import sleep, time
import datetime as dt
from datetime import datetime
from multiprocessing import Process
from threading import Thread
import threading
import requests
import mariadb
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
rq = requests.Session()
def connect_pool():
try:
pool = mariadb.ConnectionPool(
host="localhost",
port=3306,
user="root",
password="password",
pool_name="unique_pool_name",
pool_size=2, # e set size = 2 để test lỗi khi vượt quá size
database='db_name',
autocommit=True
)
return pool
except Exception as e:
logException(sys.exc_info(), str(e))
def send_order(index, mydb):
try:
mydb = getConnection() # mỗi lần call là pool connection - 1
if not mydb:
print('Cant get connection')
return
print(index)
except Exception as e:
logException(sys.exc_info(), str(e))
# nếu em bỏ comment đoạn finally này thì nó sẽ k lỗi vì sau khi chạy xong nó close thì connection trở về pool, nhưng e comment để test lỗi khi out of pool size
# finally:
# try:
# mydb.close()
# except:
# pass
def logFile(file_name, content):
try:
f = open(file_name, 'a', encoding="utf-8")
f.write(content)
f.close()
except Exception as e:
logException(sys.exc_info(), str(e))
def logException(sys_info, msg):
try:
e_type, e_object, e_traceback = sys_info
logFile('push-error.txt', f'{msg} - Line {str(e_traceback.tb_lineno)}\n')
except Exception as e:
print(str(e))
pool = connect_pool()
def getConnection():
mydb = False
try:
mydb = pool.get_connection()
except Exception as e:
logException(sys.exc_info(), str(e))
if 'No more connections from pool' in str(e):
# lỗi khi max pool size
try:
pool.close() #close pool
pool = connect_pool() # rồi tạo lại pool
# em chạy nó bị đứng ở đoạn này rồi k chạy gì tiếp nữa
return pool.get_connection()
except Exception as e:
logException(sys.exc_info(), str(e))
return mydb
while True:
try:
mydb = getConnection()
if not mydb:
print('Cant get connection')
continue
mycursor = mydb.cursor(dictionary=True)
except Exception as e:
continue
try:
order_threads = 5
list_thread_main = []
for i in range(order_threads):
t = threading.Thread(target=send_order,
args=(i, ))
list_thread_main.append(t)
for thread in list_thread_main:
thread.start()
for thread in list_thread_main:
thread.join()
except Exception as e:
logException(sys.exc_info(), str(e))
finally:
try:
mydb.close()
except:
pass