Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Go Client Libraries for Redis

Introduction

Redis is a powerful in-memory data structure store, used as a database, cache, and message broker. Go, a statically typed, compiled programming language designed by Google, provides excellent support for multi-threading. This tutorial covers how to use Go client libraries to interact with Redis.

Installing Go and Redis

Before we start, ensure you have both Go and Redis installed on your system.

To install Go, visit the official Go Downloads page and follow the instructions.

To install Redis, visit the official Redis Downloads page and follow the instructions.

Setting Up Your Go Project

Create a new directory for your Go project and initialize a new Go module.

mkdir go-redis-example
cd go-redis-example
go mod init go-redis-example

Installing Redis Go Client

We will use the popular go-redis client library for interacting with Redis. Install it using the following command:

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

Connecting to Redis

Create a new file main.go and add the following code to connect to Redis:

package main

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

var ctx = context.Background()

func main() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

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

Run the program using:

go run main.go

If the connection is successful, you will see PONG printed on the console.

Basic Redis Operations

Setting a Key

Add the following code to main.go to set a key in Redis:

err = rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
    log.Fatalf("Could not set key: %v", err)
}
                

Getting a Key

Add the following code to main.go to get the value of the key:

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

Deleting a Key

Add the following code to main.go to delete a key:

err = rdb.Del(ctx, "key").Err()
if err != nil {
    log.Fatalf("Could not delete key: %v", err)
}
                

Working with Data Structures

Lists

Lists are ordered collections of strings. Let's push and pop items from a Redis list:

err = rdb.RPush(ctx, "mylist", "item1", "item2", "item3").Err()
if err != nil {
    log.Fatalf("Could not push items to list: %v", err)
}

items, err := rdb.LRange(ctx, "mylist", 0, -1).Result()
if err != nil {
    log.Fatalf("Could not get items from list: %v", err)
}
fmt.Println("mylist:", items)
                

Hashes

Hashes are maps between string fields and string values. Let's set and get fields from a Redis hash:

err = rdb.HSet(ctx, "myhash", "field1", "value1", "field2", "value2").Err()
if err != nil {
    log.Fatalf("Could not set fields in hash: %v", err)
}

values, err := rdb.HGetAll(ctx, "myhash").Result()
if err != nil {
    log.Fatalf("Could not get fields from hash: %v", err)
}
fmt.Println("myhash:", values)
                

Conclusion

In this tutorial, we covered the basics of using Go client libraries to interact with Redis. We learned how to install the necessary tools, connect to Redis, perform basic operations, and work with data structures such as lists and hashes. With this knowledge, you can start building more complex applications using Redis and Go.