Listen for changes in redis list

吃可爱长大的小学妹 提交于 2021-02-10 18:40:45

问题


I want to write a function that constantly listens for changes in a redis list (usually when elements are pushed to the list) and pops its elements whenever the list is not empty. Then it will execute a function on the popped elements. How should I implement this?


回答1:


You can use notify-keyspace-events for that

example with Node.js but the idea is similar for other languages.

const Redis = require('ioredis')
const redis = new Redis()

;(async function () {
    redis.on('ready', () => {
        console.log('ready');

        redis.config('set', 'notify-keyspace-events', 'KEl')
        // KEl => see https://redis.io/topics/notifications to understand the configuration
        // l is meant we are interested in list event

        redis.psubscribe(['__key*__:*'])

        redis.on('pmessage', function(pattern, channel, message) {
            console.log('got %s', message);
        });
    })
})()

Example output



来源:https://stackoverflow.com/questions/58682974/listen-for-changes-in-redis-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!