我有一个订阅服务器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);
});我运行这个程序,只希望在记录在5秒内过期时看到"bar“被记录,但是,我看到的是"foo”和“bar”。
如何正确删除预先存在的subscriber.on(“消息”)侦听器?
发布于 2019-08-22 06:52:41
如果我正确理解你的问题。我认为这不是一个与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);
});https://stackoverflow.com/questions/57331923
复制相似问题