优雅的Redis轮询取数据之旅(redis轮询取数据)
Our Redis polling journey is often a surprise. I’d like to share it with you today.
Redis is an in-memory key-value store, often used as a database, cache and message broker. In some cases we may need to facilitate a “long poll” or persistent connection between a Redis server and a web server or application.
In this case, Redis comes to the rescue. Redis can be used to implement a polling system that can detect changes to the database almost in real-time, without involving client-side refreshes.
Let’s dive into some code in order to understand how this works. We’ll first need to set up a basic Redis client. We’ll use the Node.js Redis library for this, so our code will be in JavaScript.
const redis = require(‘redis’);
const client = redis.createClient();
Then we define a function which will be responsible for listening for changes in Redis.
function watchDB() {
let time = Date.now();
console.log(`Listening for changes since ${time}`);
// Start a Redis “stream” connection
let stream = client.xread(‘STREAMS’, ‘my-stream’, time, ‘COUNT’, 10);
// Return the stream’s data
return stream.then(data => {
// The data variable is an array,
// so we loop through it
data.forEach(stream => {
let key = stream[0];
let entries = stream[1];
// Now we loop through the entries
entries.forEach(entry => {
let id = entry[0];
let values = entry[1];
// Here we process each entry to
// get the item that was added
let item = values[1];
// Finally, we can evaluate it
console.log(`Item “${item}” added to stream`);
});
});
// After we process each entry,
// we call the watchDB() function agn.
watchDB();
});
}
Finally, we’ll start the function.
watchDB();
And that’s it! You now have a basic system in place that will detect changes to your Redis data in real-time. Thanks to Redis’ powerful stream feature, you can now rest easy knowing that your application and web servers will never miss any critical updates.