简体   繁体   English

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

[英]Should I create a new Redis client for each connection?

I'm looking at this code snippet: 我正在看下面的代码片段:

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 );
          } );
        } );
      } );
    });
};

It's from here: http://howtonode.org/node-redis-fun . 从这里: http : //howtonode.org/node-redis-fun

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? 另外,Redis数据库存储在哪里? In the same directory as the script? 与脚本位于同一目录中吗? How to I change that? 我该如何改变?

I'm using Redis with Node.js. 我将Redis与Node.js一起使用。

Uh, looks like they're creating a redis connection for each client. 嗯,好像他们正在为每个客户端创建一个Redis连接。 This is definitely not recommended. 绝对不建议这样做。

Redis is a database. Redis是一个数据库。 It's like MySQL. 就像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. 如果您确实担心,可以查看redis配置。 More information here: http://redis.io (the doc is really good). 此处有更多信息: http : //redis.io (该文档非常好)。

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 );
          } );
        } );
      } );
    });
};

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. 我也将redis与django-redis-backend一起使用,并在下面提到一个代码片段。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Azure Redis 集群时,我应该在我的 redis 客户端中使用集群连接吗? - Should i use cluster connection in my redis client when using Azure Redis Cluster? 我应该保持我的Redis连接持久吗? - Should I keep my redis connection persistent? 我应该在每个类方法中创建一个新的Promise吗? - Should I create a new Promise in each class method? Web和工作进程分开,是否应为每个进程打开一个新的连接? - Separate web and worker processes, should a new connection be opened for each of them? Java Websocket与服务器的每个客户端连接创建新实例 - Java websocket creates new Instance with each client connection with server 每次单击都会创建新按钮。 我应该如何为新创建的按钮创建相同的功能 - On each click new button has been created. How should I create same functionality for new created buttons Redis 创建客户端始终连接到 127.0.0.1 即使我专门更改了 redis 主机 ip - Redis create client always connecting to 127.0.0.1 even if i specifically change the redis host ip 什么时候应该用Javascript创建一个新对象? - When should I create a new object in Javascript? 从客户端获取Redis的新值 - Getting new values from Redis on client side 我应该为每个编码操作调用 new TextEncoder 吗? - Should I call new TextEncoder for the each encode operation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM