gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:23:19 26 4
gpt4 key购买 nike

我有一个订阅者 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('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);
});

关于redis - 如何删除redis中的订阅回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57331923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com