Lesson 2
Working with Numbers in Redis Using Go
Working with Numbers in Redis Using Go

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 with establishing a connection to a Redis server.

What You'll Learn

In this lesson, you will learn how to:

  1. Set numeric values in Redis using Go.
  2. Retrieve and handle numeric values in Go.

Here's the code snippet that we'll be working with:

Go
1package main 2 3import ( 4 "context" 5 "fmt" 6 "github.com/redis/go-redis/v9" 7) 8 9func main() { 10 // Create a context 11 ctx := context.Background() 12 13 // Connect to Redis 14 client := redis.NewClient(&redis.Options{ 15 Addr: "localhost:6379", 16 Password: "", // No password set 17 DB: 0, // Use default DB 18 }) 19 20 // Setting and getting string values 21 err := client.Set(ctx, "count", 5, 0).Err() 22 if err != nil { 23 panic(err) 24 } 25 26 err = client.Set(ctx, "completion_rate", 95.5, 0).Err() 27 if err != nil { 28 panic(err) 29 } 30 31 count, err := client.Get(ctx, "count").Int() 32 if err != nil { 33 panic(err) 34 } 35 36 completionRate, err := client.Get(ctx, "completion_rate").Float64() 37 if err != nil { 38 panic(err) 39 } 40 41 fmt.Printf("Course count: %d, Completion rate: %.2f\n", count, completionRate) 42}

Let's break down the code:

  • We begin by importing the necessary packages, including github.com/redis/go-redis/v9.
  • A context is created, which is needed for Redis operations in Go.
  • We establish a connection to the Redis server using redis.NewClient, passing connection options such as Addr, Password, and DB.
  • The Set method is used to store numeric values (count with a value of 5 and completion_rate with a value of 95.5) in Redis.
  • Values are retrieved using the Get method, which returns data that can be directly converted to an int or float64 using helper methods like .Int() and .Float64(), thus removing the need for decoding bytes as in some other languages. Other supported types include Int64, Float32, Uint64, etc.
Why It Matters

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.