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.
In this lesson, you will learn how to:
- Set numeric values in Redis using Go.
- Retrieve and handle numeric values in Go.
Here's the code snippet that we'll be working with:
Go1package 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 asAddr
,Password
, andDB
. - The
Set
method is used to store numeric values (count
with a value of5
andcompletion_rate
with a value of95.5
) in Redis. - Values are retrieved using the
Get
method, which returns data that can be directly converted to anint
orfloat64
using helper methods like.Int()
and.Float64()
, thus removing the need for decoding bytes as in some other languages. Other supported types includeInt64
,Float32
,Uint64
, etc.
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!