Redis: Connect, Set & Get in Go

Redis is a in-memory data store, used a lot in the backend systems of web-apps. Specifically, it’s good at helping with caching and message as it’s high performance lends itself to fast response times at retriving data.

In this blog post, we will demonstrate how to connect to Redis using Go and the go-redis library, which is one of the most popular and widely-used libraries for interacting with Redis in Go.

First you’ll need the go-redis package

1
go get -u github.com/go-redis/redis/v8

View Redis Docs  

We’ve shown an example use case below.

Remember to replace the Addr within the Options{}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/go-redis/redis/v8"
)

func main() {

	// Create a new Redis client
	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379", // Replace with your Redis server address and port
		Password: "",               // Set password if you have one, otherwise leave it empty
		DB:       0,                // Use default DB
	})

	// Create a context for Redis operations
	ctx := context.Background()

	// Test the connection to Redis
	pong, err := rdb.Ping(ctx).Result()
	if err != nil {
		log.Fatalf("Could not connect to Redis: %v", err)
	}

	fmt.Printf("Connected to Redis: %v\n", pong)

	// Perform Redis operations
	err = rdb.Set(ctx, "mykey", "gophercoding.com", 0).Err()
	if err != nil {
		log.Fatalf("Could not set key: %v", err)
	}

	value, err := rdb.Get(ctx, "mykey").Result()
	if err != nil {
		log.Fatalf("Could not get key: %v", err)
	}

	fmt.Printf("Value of mykey: %v\n", value)
}

In the example above, we do a number of things.

  1. Create a NewClient
  2. Ping the server to make sure it’s running
  3. Set a new key
  4. Then Get the key back again and print it out

Example In Action

golang redis