Development

How to Connect Redis with Go

This article will teach you to use Redis with the Go programming language.
Captain Salem 4 min read
How to Connect Redis with Go

Redis is a free and open-source in-memory database used as a cache or message broker. Redis is swift and provides reliability and scalability for applications.

Setting Up Redis Server

The first step is to ensure you have Redis installed on your system. To install Redis on any Debian based distributions, run the commands:

$ sudo apt-get update
$ sudo apt-get install redis-server

Once installed, launch the terminal and start the service as:

$ sudo /etc/init.d/redis/redis-server start

The command above will start the Redis server in the background running on port 6379. You can test that the Redis server is running by executing the command:

$ redis-cli ping.

If the server is running, the command above should return:

PONG

Opt for a WSL instance and check the instructions above to run Redis on Windows.

If you are on a macOS, you can install the Redis server using Homebrew. Open the terminal and run the command:

$ brew update
$ brew install redis

The command above should update the homebrew packages and install the Redis server.

To run the server in the background, run the command:

$ brew services start redis

Installing the go Compiler

Once you have the Redis server installed and running, open your browser and navigate to the link below:

All releases - The Go Programming Language

Select the installer package for your operating system and follow the installation instructions.

You can check the Golang compiler is installed by running the command:

$ go version

The command above should return the installed Go version. An example output is as shown below:

Connecting to Redis

Once we have the Redis server and the Go compiler installed, we can build our application. Start by running the command:

$ mkdir golang_rust
$ cd golang_rust

Next, create a new go file and call it main.go

$ touch main.go

Open the file with your favorite text editor.

$ vim main.go

Now, let us add some boilerplate code to get started.

package main
import "fmt"

func main() {
  fmt.Println("Welcome to Redis!!!")
}

The next step is to import the required package. For this tutorial, we will use the github.com/go-redis/redis package.

Add the import package as:

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

The next step is to define a client that connects to the Redis instance. We can use the NewClient method from the go-redis package.

The source code is as shown below:

package main

import (
	"fmt"
	"log"

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

func main() {
	// Create a new Redis client
	client := redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "",
		DB:       10,
	})

	// Test the connection
	pong, err := client.Ping().Result()
	if err != nil {
		log.Fatal(err)
	}

	// Return pong if the server is online
	fmt.Println(pong)
}

We define a new client using the NewClient method in the program above. The method takes a struct with the properties to connect to the Redis Server.

  1. Addr – This describes the address and port to the Redis server instance.
  2. Password – Password to the Redis instance. In our case, we have not set a password.
  3. DB – The database index to use for the application.

Next, test if the server is running by running a ping. We do this using the Ping() method, which returns pong and an err.

If the error is not nil, we log the error and then print the pong as a Result.

To test the application, run the program

$ go run main.go
PONG

Once you get PONG, we can proceed.

Adding Key-Value Pairs to Redis

Once we have connected to the server, we can add key-value pairs to the database at index 0.

The Redis package provides the Set method, which takes a key, value, and expiration duration.

By default, the expiration is set to 0, meaning the key does not expire.

To add key-value pairs, we can do.

err = client.Set("username", "user100", 0).Err()
if err != nil {
  log.Fatal(err)
}

The code above adds the specified username and value to the database. Note that the expiration value is set to 0, meaning no expiration.

Getting Values from Redis

We can also use the Get method to retrieve the value stored at a specified key. Example code is as shown below:

// get value
username, err := client.Get("username").Result()

if err != nil {
  log.Fatal(err)
}

fmt.Println("Username: ", username)

The Get method will fetch the value associated with the key "username" and print it out here.

Conclusion

This tutorial covers working with the Redis database using the Go programming language.

Golang Redis client
DataDog competitors (https://uptrace.dev/blog/datadog-competitors.html); Open Source APM (https://uptrace.dev/get/open-source-apm.html);
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.