我应该为每个连接创建一个新的Redis客户端吗?

时间:2012-06-13 07:12:51

标签: javascript database node.js 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数据库存储在哪里?在与脚本相同的目录中?如何更改?

我正在使用带有Node.js的Redis。

2 个答案:

答案 0 :(得分: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 );
          } );
        } );
      } );
    });
};

答案 1 :(得分:2)

必须实现连接池,否则代码会遇到困难。我还使用带有django-redis-backend的redis,以及下面提到的代码片段。它会给你一个想法。

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