Skip to content

Using Redis in Go - Example and Demo

homepage-banner

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.

Prerequisites

  • 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 github.com/redis/go-redis/v9.

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 (
 "context"
 "fmt"
 "log"
 "time"

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

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 {
 panic(err)
}

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 {
 log.Fatal(err)
}

// Get the value for a key
value, err := client.Get(ctx, "greeting").Result()
if err != nil {
 log.Fatal(err)
}
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 {
 log.Fatal(err)
}

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

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

// RPopr remove the last element in the list
task, err := client.RPop(ctx, "tasks").Result()
if err != nil {
 log.Fatal(err)
}
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": "john@example.com",
 "age":   25,
}).Err()
if err != nil {
 log.Fatal(err)
}

// Get hash field-values
userInfo, err := client.HGetAll(ctx, "user:1").Result()
if err != nil {
 log.Fatal(err)
}
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 {
 log.Fatal(err)
}

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 {
 panic(err)
}

Subscribe to channel

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

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

Summary

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.

Reference

  • https://www.jdon.com/71059.html
Leave your message