-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmysqlconnpool.py
executable file
·152 lines (103 loc) · 3.43 KB
/
mysqlconnpool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python2
# coding: utf-8
import copy
import logging
import Queue
import MySQLdb
logger = logging.getLogger(__name__)
retriable_err = (2006, 2013)
class MysqlConnectionPool(object):
def __init__(self, conn_argkw, options=None):
options = options or {}
options = copy.deepcopy(options)
self.options = options
self.queue = Queue.Queue(32)
self.conn_argkw = conn_argkw
if 'host' in conn_argkw:
self.name = '{host}:{port}'.format(**conn_argkw)
else:
self.name = '{unix_socket}'.format(**conn_argkw)
self.stat = {'name': self.name,
'create': 0,
'pool_get': 0,
'pool_put': 0,
}
def __call__(self, action=None):
if action is None or action == 'get_conn':
return ConnectionWrapper(self)
elif action == 'stat':
return self.stat
else:
raise ValueError(action, 'invalid action: ' + repr(action))
def get_conn(self):
try:
conn = self.queue.get(block=False)
self.stat['pool_get'] += 1
logger.debug('reuse connection:' + repr(self.stat))
return conn
except Queue.Empty:
conn = new_connection(self.conn_argkw, options=self.options)
self.stat['create'] += 1
logger.info('create new connection: ' + repr(self.stat))
return conn
def put_conn(self, conn):
try:
self.queue.put(conn, block=False)
self.stat['pool_put'] += 1
logger.debug('put connection:' + repr(self.stat))
except Queue.Full:
conn.close()
def query(self, sql, use_dict=True, retry=0):
if retry < 0:
retry = 0
retry = int(retry)
# the first attempt does not count as 'retry'
for i in range(retry + 1):
try:
with self() as conn:
return conn_query(conn, sql, use_dict=use_dict)
except MySQLdb.OperationalError as e:
if len(e.args) > 0 and e[0] in retriable_err:
logger.info(
repr(e) + " conn_query error {sql}".format(sql=sql))
continue
else:
raise
else:
raise
class ConnectionWrapper(object):
def __init__(self, pool):
self.pool = pool
self.conn = None
def __enter__(self):
self.conn = self.pool.get_conn()
return self.conn
def __exit__(self, errtype, errval, _traceback):
if errtype is None:
self.pool.put_conn(self.conn)
self.conn = None
else:
self.conn.close()
def make(conn_argkw, options=None):
return MysqlConnectionPool(conn_argkw, options=options)
def conn_query(conn, sql, use_dict=True):
if use_dict:
cur = conn.cursor(MySQLdb.cursors.DictCursor)
else:
cur = conn.cursor()
cur.execute(sql)
rst = cur.fetchall()
cur.close()
return rst
def new_connection(conn_argkw, options=None):
# useful arg could be added in future.:
# conn_argkw.init_command
options = options or {}
opt = {
'autocommit': 1,
}
opt.update(options)
conn = MySQLdb.connect(**conn_argkw)
for k, v in opt.items():
conn.query('set {k}={v}'.format(k=k, v=v))
return conn