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:
Here's the code snippet that we'll be working with:
JavaScript1import { createClient } from 'redis'; 2 3// Create and connect Redis client 4const client = createClient({ url: 'redis://localhost:6379' }); 5 6client.on('error', (err) => console.log('Redis Client Error', err)); 7 8await client.connect(); 9 10// Setting and getting numeric values 11await client.set('count', 5); 12await client.set('completion_rate', 95.5); 13 14const count = await client.get('count'); 15const completion_rate = await client.get('completion_rate'); 16 17console.log(`Course count: ${count}, Completion rate: ${completion_rate}`); 18 19await client.disconnect();
Let's break down the code:
import
syntax to import the createClient
function from the redis
library.createClient
and connected to the Redis server at 'redis://localhost:6379'
.await client.connect()
.set
method: count
with a value of 5
and completion_rate
with a value of 95.5
.get
method. Note that in JavaScript, the return type of the get
method is a string, so there's no need to decode it.await client.disconnect()
.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.
Ready to dive in? Let's move on to the practice section and get hands-on experience working with numbers in Redis!