如何删除redis中的订阅回调?

how to remove subscription callbacks in redis?

我有一个订阅者 redis 客户端实例,它在数据库中的条目过期时执行回调。我尝试添加一个初始取消订阅调用以删除以前的任何现有侦听器,但它似乎不起作用:

const setOnExpire = (onExpire) => {
  client.config('set', 'notify-keyspace-events', 'Ex', () => {
     subscriber.unsubscribe('__keyevent@0__:expired', 0); // <-- this does not seem to be doing what I was hoping it would...
     subscriber.subscribe('__keyevent@0__:expired', () => {
      subscriber.on('message', function (channel, key) {
        onExpire(key);
      });
    });
  });
};

setOnExpire(() => { console.log('foo'); });
setOnExpire(() => { console.log('bar'); }); // my intention is to replace the callback that logs "foo"
client.hmsetAsync(someKey, someAttrs).then(() => {
  client.expireAsync(someKey, 5);
});

我 运行 这个,希望只看到 "bar" 在记录在 5 秒后过期时被记录,但是相反,我看到 "foo" 和 "bar."

如何正确删除预先存在的 subscriber.on('message') 听众?

如果我没有正确理解你的问题。我认为这不是 Redis 相关的问题,它只是一个应用程序级别的问题。您只需拨打 subscriber.subscribe 一次即可设置订阅。您只想支持一个回调,因此在内部存储该回调。每次调用 setOnExpire 时,只需将回调替换为新回调即可。我不是 JavaScript 专家,下面的代码片段在我的电脑上运行良好:

var redis = require("redis");
var bluebird = require('bluebird');
bluebird.promisifyAll(redis);

var client = redis.createClient();
var subscriber = redis.createClient();

const setOnExpire = function() {
    var notify_on = false;
    var promise;
    var callback = function(key) { };
    return (onExpire) => {
        if (notify_on) {
            promise.then(()=> {
                callback = onExpire;
            });
        } else {
            promise = new Promise((resolve, reject) => {
                notify_on = true;
                client.config('set', 'notify-keyspace-events', 'Ex', () => {
                    resolve();
                });
            });

            promise.then(() => {
                subscriber.subscribe('__keyevent@0__:expired', () => {
                    subscriber.on('message', function (channel, key) {
                        callback(key);
                    });
                });
            });
        }
    };
}();


setOnExpire(() => { console.log('foo'); });
setOnExpire(() => { console.log('bar'); }); // my intention is to replace the callback that logs "foo"

client.hmsetAsync('hello', 'yesl', 'thankyou').then(() => {
  client.expireAsync('hello', 5);
});