Use Redis to cache data in Go

0
1478
Use Redis to cache data in Go
Use Redis to cache data in Go

Go and Redis have been paired together pretty for caching data, and most of Go developers will pick Redis for cache purpose. In this article, I will show you how to use Redis to cache data in Go.

Pre-requisites

You will need to have Go and redis installed on your dev machine to run the code on this tutorial. At the moment of writing this post, my Go and redis version are:


$ go version
go version go1.18.3 darwin/arm64

$ redis-cli --version
redis-cli 7.0.0

Create new Go project

Let’s start by creating a new Go project:

$ mkdir use-redis

$ cd use-redis

$ go mod init petehouston.com/use-redis

$ touch main.go

Get go-redis library

To connect with Redis, we will use go-redis library, for that, please issue this command:

$ go get github.com/go-redis/redis/v9

In case, you’re using Redis version 6, you should get library v8.

$ go get github.com/go-redis/redis/v8

and then, import the client library at the top of the main.go.

import redis "github.com/go-redis/redis/v9"

Connect to Redis

We will to instantiate a client to handle connection to Redis.

// get new client connection
redisClient := redis.NewClient(&redis.Options{
	Addr:     "localhost:6379",
	Password: "",
	DB:       0,
})

Since I’m connecting to my local Redis server, the Addr value is localhost:6379.

But if you connect to different Redis host, make sure to change the value of the Addr and Password field appropriately.

Because the prototype of redis.NewClient() returns a pointer to redis.Client, which is *redis.Client, we will need to check if the redis client is allocated or not.

if redisClient == nil {
	panic("failed to nit redis client")
}

Check connection status

To check Redis connection status, we will use Ping() method:

ctx := context.Background()
// check connection status
_, err := redisClient.Ping(ctx).Result()
if err != nil {
	panic(err)
}

By the way, to use most of methods of Redis client, we will need to pass in a context.Context instance.

Set Redis key value

To set Redis key value, use the Set() method:

key := "blog.title"

err = redisClient.Set(ctx, key, "Use Redis to cache data in Go", 0).Err()
if err != nil {
	panic(err)
}

The 4th parameter is the duration which determines how long you want to keep the key in Redis; use 0 to set no expiration.

Get Redis key value

To get Redis key value, use the Get() method:

value, err := redisClient.Get(ctx, key).Result()
if err != nil {
	panic(err)
}

fmt.Printf("%s -> %s\n", key, value)

Build and Run

Putting all the code together, this is the complete main.go:

package main

import (
	"context"
	"fmt"
	redis "github.com/go-redis/redis/v9"
)

func main() {
	redisClient := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	ctx := context.Background()

	if redisClient == nil {
		panic("failed to nit redis client")
	}
	_, err := redisClient.Ping(ctx).Result()
	if err != nil {
		panic(err)
	}

	key := "blog.title"

	err = redisClient.Set(ctx, key, "Use Redis to cache data in Go", 0).Err()
	if err != nil {
		panic(err)
	}

	value, err := redisClient.Get(ctx, key).Result()
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s -> %s\n", key, value)
}

Let’s run it to test:

$ go run main.go
blog.article -> Use Redis to cache data in Go

Conclusion

As you can see, the go-redis library makes it very simple to connect to Redis in Go.

Alrighty, that’s how you use Redis to cache data in Go. The full demo code project can be viewed at https://github.com/petehouston/golang-sample-code/tree/dev/use-redis

Have fun!