Development

How to Connect Redis with Go

In this tutorial, we will teach you how to connect your Redis database with your Go application.
Captain Salem 5 min read
How to Connect Redis with Go

How to Connect Redis with Go

Redis is a free open-source in-memory key-value database. Redis is a fantastic database that provides incredibly low latency operations for your database. This makes it a very suitable option as a caching mechanism for other databases. Redis can also act as a message broker out of the box.

It also supports a wide collection of use cases with support for numerous data structures. Redis is a also highly scalable both horizontally and vertically.

Keep in mind that this is a beginner friendly tutorial. Hence, we will focus with the initial setup and basic Redis operations.

Setting up Redis

The first step is to ensure we have Redis server installed and running on our machine.

Follow the instructions below to install Redis server on your machine.

Installing Redis on Linux

On Linux, open your terminal and run the command below:

$ sudo apt-get update
$ sudo apt-get install curl -y

Next, run use cURL to download and install the Redis keyring and repository:

$ curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
$ echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

Finally, refresh the packages and install Redis:

sudo apt-get update
sudo apt-get install redis

Once installed, start the Redis server by running the command:

sudo service redis start

Installing Redis on macOS

If you are on macOS, you can install Redis with brew by running the command:

$ brew update
$ brew install redis

Once installed, start the redis server by running the command:

$ brew services start redis

The command above should start redis. An example output is as shown:

brew services start redis  
==> Successfully started `redis` (label: homebrew.mxcl.redis)

Installing Redis on Windows

On Windows, you can run Redis by install Debian or any Debian based distribution using WSL. Then use the Linux commands to install Redis.

The second method is using Docker. Install Docker on Windows, by following the instructions below:

https://cloudenv.io/install-docker-on-windows

And run the Redis image.

Test Redis Connection

Before setting up your Go client to connect to your Redis instance, it is good to ensure that the server is up and running.

You can do so by running the command:

$ redis-cli ping

If the server is running, the command above should return PONG as shown:

$ redis-cli ping
PONG

Setting up our Go Client

The next step is to create a Go client. Let us start by installing the Go compiler on our system. Check the following tutorials to learn more.

  1. How to install Golang on Windows
  2. How to install Golang on macOS)
  3. How to install Golang on Linux)

Once configured start by creating a directory to store our code. In our example, we will use our home directory

cd ~

Next. create directory and navigate into it:

mkdir golang_client
cd golang_client

In the working directory, initialize a new file to store our Golang code:

touch main.go

Open the file with your favorite text editor:

vim main.go

In the main.go file, let us the basic structure of our Golang code:

package main

func main() {
    
}

The code above holds the main function where we are going to store the code for our Golang client.

Installing Redis Client

To interact with our Redis database from the Golang client, we will need the redis client. In our example, we will use the golang-redis client as provided in the link below:

GitHub - redis/go-redis: Redis Go client
Redis Go client. Contribute to redis/go-redis development by creating an account on GitHub.

In our working directory, run the command below to initialize go modules

go mod init main

This will create a new go.mod file where we will include the packages we wish to install.

Go back to the main.go file and add the import statement as shown:

package main
import (
    "github.com/go-redis/redis/v9"
)
func main() {

}

Go back to your terminal Window and run the command below:

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

The command above will install the golang-redis package.

Ensure that the go.mod file includes entries as shown below:

module main
go 1.15
require github.com/go-redis/redis/v9 v9.0.0-beta.1

Connecting to Redis

Once we have the required packages installed, we can go ahead and connect to the Redis database. In the main.go file, add the code as shown below:

package main

import (
    "context"

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

var ctx = context.Background()

func RedisClient() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "",
        DB:       15, // use the last database
    })
}
func main() {

}

In the code above, we start by importing the context module. We use context to handle cancellation signals, scoped valuets, etc.

The context.Background() function, returns an empty context with no values or deadlines.

In the next step, we define a function called RedisClient . This function allows us to define the details for connecting to the Redis server.

Inside the function, we use the redis.NewClient() to initialize a new client. We also specify the details as a struct including the Address to the Redis server, the password (if the server is secured) and the target database.

In our example, we are using the database at index 15 (the last database) to test.

We then test if the we can access the server from our Go application by adding the code below inside the RedisClient function:

    pong, err := rdb.Ping(ctx).Result()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(pong)

Here, we use the Ping() function to test if we can access the server. In the main function, call the RedisClient() function as shown:

func main() {
    RedisClient()
}

We can then run the program as shown:

$ go run main.go

The code should return PONG.

Ensure you have specified the correct details to the Redis server.

Set Key-Value Pair

Now that we have successfully connected to the Redis server, let us see how we can add data to the database using Go.

The Redis-go client provides us with the Set method that allows us to add a key-value pair to the database. The method takes a key, value, and the expiration duration as the parameter. If the expiration parameter is set to 0, the key-value pair will not expire.

Take the example code below:

    err = rdb.Set(ctx, "username", "geekbits", 0).Err()
    if err != nil {
        log.Panic(err)
    }

In the code above, we use the rdb.Set() function to pass the key "username" and the value "geekbits". We also set the expiration duration as 0. This means the key is not volatile.

Once we run the code above, it should print PONG and add a the specified key-value pair to the target database.

Get Values

The next step is to retrieve values from the database. Luckily the golang-redis package provides us with the Get() function to do just that. The function takes the key whose value we wish to retrieve as the parameter.

An example code is as shown:

    value, err := rdb.Get(ctx, "username").Result()
    if err != nil {
        log.Panic(err)
    }
    fmt.Println(value)

In the code above, we use the Get() function to retrieve the value associated with the key “username”. Running the code above should return:

$ go run main.go 
PONG
geekbits

And with that, you have successfully, retrieved a value from the Redis database with Go.

Conclusion

That’s it for this one. In this short beginner-friendly article, we learned how to connect Redis database to our Golang application. This tutorial provides the main fundamental concepts you need to know when working with Redis in Go.

There will be a part 2 where we go over how to store other data types and perform advanced operations. Make sure to subscribe to the newsletter to get notified.

Until then, Thanks for reading & See you again soon~~~!

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.