我想在用户的会话被销毁/超时时运行一个函数。在使用redis会话存储的express中使用nodejs有办法吗?
答案 0 :(得分:7)
会话商店本身继承自EventEmitter:
https://github.com/senchalabs/connect/blob/master/lib/middleware/session/store.js
虽然没有一个实现发出要绑定的事件,包括redis store:
https://github.com/visionmedia/connect-redis/blob/master/lib/connect-redis.js
你可以很容易地将connect-redis分叉并自己破解这些事件,以便你可以在你需要的地方绑定它们....
RedisStore.prototype.destroy = function(sid, fn){
sid = this.prefix + sid;
this.client.del(sid, fn);
};
变为
RedisStore.prototype.destroy = function(sid, fn){
sid = this.prefix + sid;
this.client.del(sid, fn);
this.emit('destroy');
};
然后你可以绑定到“destroy”事件......
var connect = require('connect')
, RedisStore = require('connect-redis')(connect);
var store = new RedisStore;
store.on('destroy', function() {
// session was destroyed
});
connect.createServer(
connect.cookieParser(),
connect.session({ store: store, secret: 'keyboard cat' })
);