[Django]-How to use connection pooling for redis.StrictRedis?

4👍

Each Redis instance that you create in turn all instances will create their own connection pool.You can overwrite this behaviour by using the singleton design in Python as below:

import redis

class RedisOperation(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
            cls.instance=redis.StrictRedis(connection_pool=pool)
        return cls.instance

obj1=RedisOperation()
print(id(obj1))

obj2 = RedisOperation()
print(id(obj2))

Both above objects are referring to same redis connection pool.

For More details, please refer to redis docs

Leave a comment