python使用连接池操作redis数据库
环境准备
准备好ubntu18.04虚拟机,并且安装redis,pyton等环境。
环境准备
概念
本示例采用单例模式,创建redis连接池。这样可以在应用程序的任何地方使用相同的连接池,节省系统开销
程序示例
'''
使用单例模式创建redis 链接池
'''
from redis import ConnectionPool
import threading
import time
class redis_pool(object):
_instance_lock = threading.Lock()
pool = ConnectionPool(host='localhost', port=6379, db=0)
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(redis_pool, "_instance"):
with redis_pool._instance_lock:
if not hasattr(redis_pool, "_instance"):
redis_pool._instance = redis_pool(*args, **kwargs)
return redis_pool._instance
if __name__ == "__main__":
def task(arg):
obj = redis_pool.instance()
print(obj)
print(obj.pool)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(2)
print('end')
obj = redis_pool.instance()
print(obj)
print(obj.pool)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
运行结果
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>
ConnectionPool>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20