python使用连接池操作redis数据库

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)    

运行结果

<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>
<__main__.redis_pool object at 0x7fdf6c0467f0>
ConnectionPool>

你可能感兴趣的:(AGV)