Should I create a new Redis client for each connection?

前端 未结 2 1372
不知归路
不知归路 2021-01-15 21:12

I\'m looking at this code snippet:

var addSnippet = function( req, res ) {
  getPostParams( req, function( obj ) {
      var r = redis.createClient();

              


        
2条回答
  •  醉话见心
    2021-01-15 21:53

    Connection pooling has to be implemented otherwise the code will run into a soup. I also use redis with django-redis-backend, with a code snippet mentioned below. It will give you an idea.

    class CacheConnectionPool(object):
    
        def __init__(self):
            self._connection_pools = {}
    
        def get_connection_pool(self, host='127.0.0.1', port=6379, db=1,
                                password=None, parser_class=None,
                                unix_socket_path=None):
            connection_identifier = (host, port, db, parser_class, unix_socket_path)
            if not self._connection_pools.get(connection_identifier):
                connection_class = (
                    unix_socket_path and UnixDomainSocketConnection or Connection
                    )
                kwargs = {
                    'db': db,
                    'password': password,
                    'connection_class': connection_class,
                    'parser_class': parser_class,
                }
                if unix_socket_path is None:
                    kwargs.update({
                        'host': host,
                        'port': port,
                    })
                else:
                    kwargs['path'] = unix_socket_path
                self._connection_pools[connection_identifier] = redis.ConnectionPool(**kwargs)
            return self._connection_pools[connection_identifier]
    
    pool = CacheConnectionPool()
    

提交回复
热议问题