Node.js + Express + Redis, when to close connection?

我是研究僧i 提交于 2019-12-08 15:00:19

问题


I have a Node application that uses Express and node_redis. I'm following the approach outlined in the Learning Node book and creating a single client for the life of the application. Given this approach, when do I call close() on the redis client? Do I even need to?

Relevant code

var express = require( 'express' ),
    redis = require( 'redis' );

var app = express(),
    config = require( './config/application' )[ app.get( 'env' ) ];

// create Redis client
var redisClient = redis.createClient();
redisClient.on( 'error', function( err ) {
  console.log( 'Error' + err );
} );
// select the database
redisClient.select( config.redis_database );

...
/* more setup, route defintions, etc. */
...

http.createServer( app ).listen( 4000, function() {
  console.log( 'Server started and ready for action!' );
});

回答1:


You have a couple options.

  1. Be lazy and set an idle timeout for all clients on the redis server. Then when a client is idle for too long the server would just kill their connection.
  2. Kill the connection when the node process exits.

.

process.on("exit", function(){
    redisClient.quit();
});



回答2:


: The question was 3 years ago and you might get answer already, anyway this might be useful for some new people.

You can make nodejs process listens to SIGINT which is interrupt sent from keyboard via the following code

process.on('SIGINT', function() {
    redisClient.quit();
    console.log('redis client quit');
});

Then you can either Ctrl+C from the keyboard, or send such signal via kill -SIGINT <process id>. When that happens, that code will be executed.

This is when we don't know exactly when to quit redis client, or we want external control to cleanly quit/clear resource we was using.



来源:https://stackoverflow.com/questions/22387187/node-js-express-redis-when-to-close-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!