2012-06-13 69 views
1

我在看这个代码片段:我应该为每个连接创建一个新的Redis客户端吗?

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

     r.stream.on('connect', function() { 
     r.incr('nextid' , function(err, id) { 
      r.set('snippet:'+id, JSON.stringify(obj), function() { 
      var msg = 'The snippet has been saved at <a href="/'+id+'">'+req.headers.host+'/'+id+'</a>'; 
      res.respond(msg); 
      }); 
     }); 
     }); 
    }); 
}; 

从这儿:http://howtonode.org/node-redis-fun

我不太明白发生了什么事。例如,我认为Redis客户端是数据库和程序员之间的某种接口,但现在看来他们正在为每个代码提交创建一个新的客户端(他们在本教程中构建的应用程序接受代码片段提交并将它们存储在数据库中)!

另外,Redis数据库的存储位置在哪里?在与脚本相同的目录中?我如何改变它?

我使用Redis和Node.js.

回答

4

呃,看起来他们正在为每个客户创建一个redis连接。这绝对不是建议。

Redis是一个数据库。这就像MySQL。您可以通过客户端访问它,但它是在您的服务器上运行的程序。数据由它处理,所以你不必担心它在哪里。如果您担心,可以查看redis配置。更多的信息在这里:http://redis.io(该文件非常好)。

“修理”的代码,并且只使用一个客户端,你必须使用它像这样:

/** 
* Move this at the top, this way it's not run once per client, 
* it is run once the node program is launched. 
*/ 
var r = redis.createClient(); 

var addSnippet = function(req, res) { 
    getPostParams(req, function(obj) {  
     r.stream.on('connect', function() { 
     r.incr('nextid' , function(err, id) { 
      r.set('snippet:'+id, JSON.stringify(obj), function() { 
      var msg = 'The snippet has been saved at <a href="/'+id+'">'+req.headers.host+'/'+id+'</a>'; 
      res.respond(msg); 
      }); 
     }); 
     }); 
    }); 
}; 
+3

Redis的库也许不是同时请求相同的连接准备,所以你应该只使用所有请求一个连接,如果你是100%肯定的是,Redis的库能正确处理这个问题。 –

2

连接池实现的问题,否则代码将运行到一个汤。我还使用redis和django-redis-backend,并提供了下面提到的代码片段。它会给你一个想法。

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() 
相关问题