Skip to content

Using Redis in Go - Example and Demo


Redis is an open-source in-memory data structure store that can be used as a cache, message broker, or persistent key-value database. In this article, we will explore how to integrate Redis with a Golang application to leverage Redis’s powerful features for efficient data storage and retrieval.


  • Make sure Redis is installed on your computer or that you have access to a Redis server.
  • Install the Redis Golang client using go get

Setting up the Redis connection:

To start using Redis in a Golang project, import the Redis client package and establish a connection with the Redis server. Here is an example:

package main

import (


var ctx = context.Background()

func main() {
// Connect to Redis
 client := redis.NewClient(&redis.Options{
  Addr:     "localhost:6379",// replace to your redis adddress
  Password: "",
  DB:       0,

// Ping Redis
 pong, err := client.Ping(ctx).Result()
if err != nil {
  log.Fatal("Error connecting to Redis:", err)
 fmt.Println("Connected to Redis:", pong)

Another commonly used method is to use a connection string:

opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
if err != nil {

client := redis.NewClient(opt)

Basic Operations

1 Set and Get Values

Please note that each Redis command accepts a context, which you can use to set timeouts or propagate certain information, such as tracing context.

Let’s perform some basic operations like setting and getting values in Redis.

// Set a key-value pair
err := client.Set(ctx, "greeting", "Hello, Redis!", 0).Err()
if err != nil {

// Get the value for a key
value, err := client.Get(ctx, "greeting").Result()
if err != nil {
fmt.Println("Greeting:", value)

2 Using Lists

The list data structure provided by Redis can be used to implement queues.

// LPush nsert values at the head of the list
err = client.LPush(ctx, "tasks", "Task 1", "Task 2").Err()
if err != nil {

// RPush insert values at the back/ tail of the list
err = client.RPush(ctx, "tasks", "Task 1", "Task 2").Err()
if err != nil {

// LPop remove the first element in the list
task, err := client.LPop(ctx, "tasks").Result()
if err != nil {
fmt.Println("Popped Task:", task)

// RPopr remove the last element in the list
task, err := client.RPop(ctx, "tasks").Result()
if err != nil {
fmt.Println("Popped Task:", task)

3 Using Hashes

Hashes in Redis allow you to store multiple field-value pairs under a single key.

// Set hash field-values
err = client.HSet(ctx, "user:1", map[string]interface{}{
 "name":  "John Doe",
 "email": "",
 "age":   25,
if err != nil {

// Get hash field-values
userInfo, err := client.HGetAll(ctx, "user:1").Result()
if err != nil {
fmt.Println("User Info:", userInfo)

Please note that in older versions of Redis server (redis < 4.0), HSet only supports a single key-value pair, while HMSet is used for multiple field-value arguments. However, starting from redis 4.0, HMSet has been marked as deprecated and may no longer be supported in the future.

In Redis >= 4.0, use HSet:

client.HSet(ctx, "myhash", Per{Name: "hi", Age: 20})

In Redis < 4.0, use HMSet:

client.HMSet(ctx, "myhash", Per{Name: "hi", Age: 20})

Handling errors with redis.Nil

go-redis exports the redis.Nil error and returns it when the Redis server responds with (nil). You can use redis-cli to check the response returned by Redis.

In the example below, we use redis.Nil to differentiate between empty string response and nil response (key does not exist):

val, err := client.Get(ctx, "key").Result()
switch {
case err == redis.Nil:
 fmt.Println("key does not exist")
case err != nil:
 fmt.Println("Get failed", err)
case val == "":
 fmt.Println("value is empty")

Not only GET command will return nil response, for example, BLPOP and ZSCORE will also return redis.Nil.

Advanced Operations

Expiring Keys

Set expiration time for keys in Redis.

// Set a key with expiration time
err = client.Set(ctx, "temporary", "I will expire soon!", 10*time.Second).Err()
if err != nil {

Subscribe to a Pub/Sub channel

Redis supports publishing/subscribing to messages.

Here is how to publish a message:

err := client.Publish(ctx, "mychannel", "payload").Err()
if err != nil {

Subscribe to channel

pubsub := client.Subscribe(ctx, "mychannel")
channel := pubsub.Channel()

// Listen for messages
for {
 msg, ok := <-channel
if !ok {
 fmt.Println("Received message from channel:", msg.Payload)


This guide explains how to use Redis in Golang. Redis provides powerful caching, real-time analytics, and other features. When building Golang applications, consider leveraging Redis to improve performance and scalability. Explore other Redis commands and configurations as per your project requirements.


Leave your message