Welcome back to our Redis course! Now that you know how to connect to a Redis server, it's time to move forward and explore how to work with numbers in Redis. This unit builds on our previous lesson, so make sure you're comfortable establishing a connection to a Redis server.
In this lesson, you will learn how to:
- Set numeric values in Redis.
- Retrieve and log numeric values.
Here's the code snippet that we'll be working with:
Let's break down the code:
- We start by importing the
ioredislibrary to access its functionalities. - A Redis client is created using
new Redis(), which connects to the default Redis server. - Numeric values are set using the
setmethod:countwith a value of5andcompletion_ratewith a value of95.5. - These values are retrieved using the
getmethod. Note that the retrieved values are strings, so they can be directly logged. Note that the retrieved values are strings, so they can be directly logged. This means that when you retrieve a value usingget, it will always be a string. If you need to perform mathematical operations on the retrieved number, you must convert it back to a number usingparseInt()orparseFloat()like this:
Working with numbers in Redis is crucial because many real-world applications involve numeric data. From tracking user statistics to monitoring system performance, managing numbers in Redis allows you to perform a variety of useful operations efficiently. By mastering these basic operations with numbers, you'll be well-prepared to tackle more complex tasks and optimize your applications.
