-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspmpool.py
More file actions
200 lines (190 loc) · 6.43 KB
/
spmpool.py
File metadata and controls
200 lines (190 loc) · 6.43 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from queue import Queue
from threading import Thread
from pymysql import connections
from datetime import datetime
from time import sleep
class Connection(object):
def __init__(self, pool, **kwargs):
self._pool = pool
self._closed = False
self.proto = connections.Connection(**kwargs)
self.proto.autocommit(True)
def _restore(self):
self._closed = False
self.proto.autocommit(True)
self.result = None
def begin(self):
self.proto.autocommit(False)
def commit(self):
if not self.proto.autocommit_mode:
self.proto.commit()
self.proto.autocommit(True)
def rollback(self):
self.proto.rollback()
def execute(self, sql):
cursor = self.proto.cursor()
cursor.execute(sql)
self.result = ResultProxy(cursor)
return self.result
def close(self):
if not self._closed:
self._pool.put(self)
self._closed = True
def shutdown(self):
self.proto.close()
class ConnectionPool(object):
_configs = {
'dev':{
'user':'root',
'password':'123456',
'database':'test',
'host':'127.0.0.1',
'port':3306,
'charset':'utf8',
'init_size':10
}
}
_instances = {}
_resources = []
_res_queue = Queue(20000 * 2)
def __init__(self, init_size, **kwargs):
self._init_size = init_size
self.kwargs = kwargs
self.startup()
def put(self, conn) : self._queue.put(conn)
def get(self):
if self.stopped:
print("this connection pool is stopped. run this connection pool's startup() is useful!")
return
try : conn = self._queue.get_nowait()
except Exception as e:
print('the init_size of ConnectionPool is so small ! waiting...')
conn = self._queue.get()
ConnectionPool._resources.append({'pdate':datetime.now(),'value':conn})
conn._restore()
return conn
def size(self) : return self._queue.qsize()
def useable(self) : return True if self._queue.qsize() > 0 else False
def extend(self, poolorsize=10):
if type(poolorsize) == ConnectionPool:
while poolorsize.readycount() > 0 : self._queue.put(poolorsize.get())
elif type(poolorsize) == int:
for i in range(poolorsize):
self._queue.put(Connection(self, **self.kwargs))
else : return
def startup(self):
try:
self._queue = Queue(20000) # the queue of connection wrapper
for i in range(self._init_size):
self._queue.put(Connection(self, **self.kwargs))
except Exception as e:
print('Warning:%s' % e)
print('%d connections create successful !' % self._queue.qsize())
self.stopped = False
def shutdown(self):
while self._queue.qsize() > 0 : self._queue.get().shutdown()
self.stopped = True
class ResultProxy(object):
def __init__(self, cursor):
self.cursor = cursor
self.rowcount = cursor.rowcount
def first(self):
data = self.cursor.fetchone()
row = None
if data:
row = self._2row(data, self.cursor.description)
self.cursor.scroll(-1)
ConnectionPool._resources.append({'pdate':datetime.now(),'value':self.cursor})
return row
def fetchall(self):
data = self.cursor.fetchall()
result = []
desc = self.cursor.description
for item in data : result.append(self._2row(item, desc))
if self.rowcount > 0 : self.cursor.scroll(-self.rowcount)
ConnectionPool._resources.append({'pdate':datetime.now(),'value':self.cursor})
return result
def _2row(self, proto_row, desc):
row = _Row()
for i in range(len(desc)):
col_name = desc[i][0]
if col_name.isdigit():
col_name = 'col%d' % i
row.index.append(col_name)
setattr(row, col_name, proto_row[i])
return row
def __iter__(self):
result = self.fetchall()
self.allresult = result
return result.__iter__()
def __next__(self):
self.allresult.__next__()
class _Row(object):
def __init__(self) : self.index = []
def __getitem__(self, key):
if type(key) == int:
return getattr(self, self.index[key])
else:
return getattr(self, key)
def add_config(
pool_name,
user,
password,
database,
host='127.0.0.1',
port=3306,
charset='utf8',
init_pool_size=10):
ConnectionPool._configs.update({
pool_name:{
'user':user,
'password':password,
'database':database,
'host':host,
'port':port,
'charset':charset,
'init_size':init_pool_size
}
}
)
def spmpool(pool_name='dev'):
if pool_name not in ConnectionPool._instances.keys():
if pool_name not in ConnectionPool._configs.keys():
print('none this config.')
return
else:
config = ConnectionPool._configs[pool_name]
ConnectionPool._instances.update(
{
pool_name:ConnectionPool(
config['init_size'],
host=config['host'],
user=config['user'],
password=config['password'],
database=config['database'],
port=config['port'],
charset=config['charset']
)
}
)
return ConnectionPool._instances[pool_name]
def _resource_monitor(condition):
while condition:
for r in ConnectionPool._resources:
if (datetime.now() - r['pdate']).seconds > 300:
ConnectionPool._resources.remove(r)
ConnectionPool._res_queue.put(r['value'])
sleep(600)
print('Monitor stopped.')
def _resource_cleaner(condition):
while condition:
r = ConnectionPool._res_queue.get()
if r : r.close()
print('Cleaner stopped.')
def _spmpool_startup():
Thread(target=_resource_monitor, args=(True,)).start()
Thread(target=_resource_cleaner, args=(True,)).start()
def shutdown():
for instance in ConnectionPool._instances.values():
instance.shutdown()
_spmpool_startup()