Should I create a new Redis client for each connection?

前端 未结 2 1373
不知归路
不知归路 2021-01-15 21:12

I\'m looking at this code snippet:

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

              


        
2条回答
  •  青春惊慌失措
    2021-01-15 21:45

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

    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 '+req.headers.host+'/'+id+'';
                res.respond( msg );
              } );
            } );
          } );
        });
    };
    

提交回复
热议问题