我应该为每个连接创建一个新的Redis客户端吗? [英] Should I create a new Redis client for each connection?

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

I don't quite understand what's going on. From example, I figured that the Redis client is a some kind of interface between the database and the programmer, but now it seems that they are creating a new client for each code submit (the app they are building in the tutorial is accepts code snippet submits and stores them in a database)!

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

Also, where are Redis databases stored? In the same directory as the script? How to I change that?

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

I'm using Redis with Node.js.

推荐答案

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

Uh, looks like they're creating a redis connection for each client. This is definitely not recommended.

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

Redis is a database. It's like MySQL. You can access it through a client, but it's a program running on your server. The datas are handled by it, so you don't have to worry about where it is. If you do worry, you can look at redis configuration. More information here: http://redis.io (the doc is really good).

要修复代码,并且只使用一个客户端,您必须像这样使用它:

To "fix" the code, and use only one client, you'd have to use it like this:

/**
 * 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客户端吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆