Let's start with a basic example illustrating how to set a Redis key/value pair for our Redis cache of famous animals. Here's the Node.js code to accomplish the goal:
We will use this same pattern repeatedly so let's review some of the details.
In line 1, we use
require to include the
ioredis package and make it available in our program.
In line 3, we create a new
Redis instance to enable us to interact with the Redis server. Since we will be running our Node program on the same system as the Redis server, we don't have to supply any additional arguments in the constructor. To connect to a host called
raspi on port 6379, we would create a new Redis instance using this syntax instead:
const port = 6379; const host = 'raspi'; const redis = new Redis(port, host);
Likewise, if we are authenticating with a password, there are other arguments that can be passed as described in the ioredis documentation.
We wrap all our commands inside an async function starting in line 5.
In line 7, we issue the Redis
set command to set our key (
cat) to a value of
We disconnect from the Redis server in line 11. Without this command, our Node.js console application will remain suspended and not return to the command prompt.
Finally, in line 14, we invoke our async function called
main to set our code in motion.
The ioredis API also provides an event handler to notify us when a connection has been established. Here's a modified version of our code above with this detection in place:
We subscribe to the event on line 15 to ensure we are informed when a connection to the Redis server is established. The remaining code examples will not include this functionality; however, we wanted to make you aware of its existence.
In the above code example, we set the value in the key/value pair and immediately turn around and get the value in line 10. The async/await syntax is definitely our friend here as it makes it much easier to write maintainable code without a lot of additional ceremony.