我应该为每个连接创build一个新的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客户端是数据库和程序员之间的某种接口,但现在看来他们正在为每个代码提交创build一个新的客户端(他们在教程中构build的应用程序接受代码片段提交并将它们存储在数据库中)!

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

我在Node.js中使用Redis

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

Redis是一个数据库。 这就像MySQL。 您可以通过客户端访问它,但它是在您的服务器上运行的程序。 数据由它处理,所以你不必担心它在哪里。 如果你担心,你可以看看redis的configuration。 更多信息在这里: 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 ); } ); } ); } ); }); }; 

连接池必须被执行,否则代码将变成汤。 我也使用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()