Redis basics
Redis basics
In this article, we will demonstrate only the Set and Get operations in Redis using Golang.
For this article, we will use this package:
go get github.com/redis/go-redis/v9
This is the complete code; below, we will discuss the most important points:
package main
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
Protocol: 2,
})
ctx := context.Background()
err := client.Set(ctx, "myKey", "myValue", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get(ctx, "myKey").Result()
if err != nil {
panic(err)
}
fmt.Println("value of myKey:", val)
}
This is one way to configure a new client for Redis.
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
Protocol: 2,
})
SET
To perform the Set operation, we chain the Set function followed by the Err function.
err := client.Set(ctx, "myKey", "myValue", 0).Err()
In the Set function, we pass the context, key, value, and the duration the key should last as parameters. If we pass 0, it means the key/value pair will never expire.
GET
To perform the Get operation, we chain the Get function followed by the Result function.
val, err := client.Get(ctx, "myKey").Result()