Command batching

Redis can receive multiple commands at once. The redis module has a multi method, which sends commands in batches.

Let's copy the redis-app folder to redis-batch-app.

Now we'll modify the add function as follows:

function add ({author, quote}, cb) { 
const key = `Quotes: ${uuid()}`
client
.multi()
.hmset(key, {author, quote})
.sadd(`Author: ${params.author}`, key)
.exec((err, replies) => {
if (err) return cb(err)
if (replies[0] === "OK") console.log('Added... ')
cb()
})

}

We also need to alter the first if statement to account for the now asynchronous nature of the add function:

if (params.author && params.quote) { 
add(params, (err) => {
if (err) throw err
list((err) => {
if (err) console.error(err)
client.quit()
})

})
return
}

The call to client.multi essentially puts the redis client into batch mode, queueing each subsequent command. When exec is called, the list of commands is then sent to Redis and executed all in one go.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.17.40