Node.js + Express + Redis什么时候closures连接?
我有一个使用Express和node_redis的节点应用程序。 我遵循学习节点手册中概述的方法,并为应用程序的整个生命周期创build单个客户端。 鉴于这种方法,我什么时候在redis客户端上调用close()
? 我甚至需要吗?
相关的代码
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!' ); });
你有几个选项。
- 懒惰,并为redis服务器上的所有客户端设置空闲超时。 然后,当一个客户端闲置太久,服务器就会杀死他们的连接。
- 节点进程退出时终止连接。
。
process.on("exit", function(){ redisClient.quit(); });
:问题是3年前,你可能已经得到答案,无论如何,这可能是有用的一些新的人。
您可以让nodejs进程侦听通过以下代码从键盘发送的中断的SIGINT
process.on('SIGINT', function() { redisClient.quit(); console.log('redis client quit'); });
然后你可以从键盘上Ctrl+C
,或者通过kill -SIGINT <process id>
发送这样的信号。 当发生这种情况时,该代码将被执行。
这是当我们不知道什么时候退出Redis客户端,或者我们希望外部控制干净地退出/清除我们正在使用的资源。