Go

Learn how to connect to Redis databases in Sealos DevBox using Go

This guide will walk you through the process of connecting to a Redis database using Go within your Sealos DevBox project.

Prerequisites

Install Required Packages

In your Cursor terminal, install the necessary packages:

go get github.com/go-redis/redis
go get github.com/joho/godotenv

These commands install:

  • github.com/go-redis/redis: A Redis client for Go
  • github.com/joho/godotenv: A Go port of the Ruby dotenv library

Connection Setup

Set up the environment variables

First, let's set up the environment variables for our database connection. Create a .env file in your project root with the following content:

.env
REDIS_HOST=your_redis_host
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password

Replace the placeholders with your actual Redis credentials from the Database app in Sealos.

Create the main.go file

Create a new file named main.go with the following content:

main.go
package main
 
import (
	"fmt"
	"log"
	"os"
 
	"github.com/go-redis/redis"
	"github.com/joho/godotenv"
)
 
func main() {
	// Load environment variables from .env file
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
 
	// Create a new Redis client
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT")),
		Password: os.Getenv("REDIS_PASSWORD"),
		DB:       0, // use default DB
	})
	// Test the connection
	pong, err := client.Ping().Result()
	if err != nil {
		log.Fatal("Could not connect to Redis: ", err)
	}
	fmt.Println("Connected to Redis: ", pong)
	// Set a key
	err = client.Set("mykey", "Hello from Sealos DevBox!", 0).Err()
	if err != nil {
		log.Fatal("Could not set key: ", err)
	}
	// Get a key
	val, err := client.Get("mykey").Result()
	if err != nil {
		log.Fatal("Could not get key: ", err)
	}
	fmt.Println("mykey:", val)
 
	// Close the connection
	err = client.Close()
	if err != nil {
		log.Fatal("Error closing Redis connection: ", err)
	}
	fmt.Println("Redis connection closed successfully")
}

This code demonstrates how to connect to Redis, set a key, get a key, and close the connection.

Usage

To run the application, use the following command in your Cursor terminal:

go run main.go

This will execute the main function, demonstrating the connection to Redis, setting and getting a key, and closing the connection.

Best Practices

  1. Use environment variables for Redis credentials.
  2. Always handle potential errors using proper error checking.
  3. Use a context for operations that might need to be cancelled or timed out.
  4. Close the Redis connection after operations are complete.
  5. Consider using connection pooling for better performance in production environments.

Troubleshooting

If you encounter connection issues:

  1. Verify your Redis credentials in the .env file.
  2. Ensure your Redis database is running and accessible.
  3. Check for any network restrictions in your DevBox environment.
  4. Confirm that the required packages are correctly installed.

For more detailed information on using Redis with Go, refer to the go-redis documentation.

Edit on GitHub

Last updated on

On this page