如何使用nodejs和express向会话(redis)添加事件监听器?

发布于 2024-12-10 06:19:25 字数 71 浏览 0 评论 0原文

我想在用户会话被破坏/超时时运行一个函数。有没有办法使用 redis 会话存储在 Nodejs 中与 Express 一起使用?

I would like to run a function whenever a user's session is destroyed/times out. Is there a way to do with in nodejs with express using a redis session store?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方的巷 2024-12-17 06:19:25

会话存储本身继承自 EventEmitter:

https://github .com/senchalabs/connect/blob/master/lib/middleware/session/store.js

尽管没有一个实现会发出事件供您绑定,包括 redis 存储:

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

然后你可以绑定到“破坏”事件...

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

The session store's themselves inherit from EventEmitter:

https://github.com/senchalabs/connect/blob/master/lib/middleware/session/store.js

Although none of the implementations emit events for you to bind to, including the redis store:

https://github.com/visionmedia/connect-redis/blob/master/lib/connect-redis.js

You could quite easily fork connect-redis and hack these events in yourself so that you may bind to them where you need to....

RedisStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.del(sid, fn);
  };

becomes

RedisStore.prototype.destroy = function(sid, fn){
    sid = this.prefix + sid;
    this.client.del(sid, fn);
    this.emit('destroy');
  };

Then you may bind to the "destroy" event...

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' })
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文