go-redis

path: full-stack/go-chi-server/go-redis.md

- **fileName**: go-redis
- **Created on**: 2024-09-16 18:30:15

now staring how to using redis with the go lang

Redis Client Example in Go

Code Explanation

// main.go file
package main
import (
    "context"
    "fmt"
    "log"
    "time"

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

// Global context to use with Redis operations
var ctx = context.Background()

// Main function that initializes the Redis client and performs various operations
func main() {
    // Connect to Redis
    client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379", // Replace with your Redis server address
        Password: "",                // No password for local development
        DB:       0,                 // Default DB
    })

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

    // Uncomment the lines below to test different Redis operations
    // redisAddingValues(client)
    // redisListTask(client)
    // ErrorRedis(client)
    // ExpireKeys(client)

    // Use a goroutine to handle subscription (non-blocking)
    go subscripeChannel(client)

    // Simulate publishing a message after a delay (for testing purposes)
    time.Sleep(2 * time.Second) // Wait 2 seconds before publishing
    err = client.Publish(ctx, "mychannel", "Hello from Redis!").Err()
    if err != nil {
        log.Fatal("Error publishing message:", err)
    }

    // Keep the main function alive to keep receiving messages
    select {} // An empty select blocks the main function indefinitely
}

redisAddingValues Function

// redisAddingValues demonstrates how to add values to Redis
func redisAddingValues(client *redis.Client) {
    err := client.Set(ctx, "foo", "more foo", 0).Err() // 0 means no expiration
    if err != nil {
        log.Fatal(err)
    }
    value, err := client.Get(ctx, "foo").Result() // Retrieve the value of 'foo'
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The value for 'foo' from Redis: %v\n", value)
}
Notes:
Tip:

redisListTask Functionk

func redisListTask(client *redis.Client) {
// redisListTask demonstrates how to work with Redis lists
    var err error

    // Use DEL command to remove the entire key 'tasks' and its data
    err = client.Del(ctx, "tasks").Err()
    if err != nil { log.Fatal(err) }

    // LPush insert 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) }

    // Retrieve all elements from the list using LRANGE
    // 0 is start, -1 means end (all elements)
    tasks, err := client.LRange(ctx, "tasks", 0, -1).Result() 
    if err != nil { log.Fatal(err) }
    fmt.Println("All tasks:", tasks)

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

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

    // Retrieve all remaining elements
    tasks, err = client.LRange(ctx, "tasks", 0, -1).Result()
    if err != nil { log.Fatal(err) }
    fmt.Println("Remaining tasks:", tasks)
}

Notes:

Tip:

ErrorRedis Function

// ErrorRedis handles errors when working with Redis
func ErrorRedis(client *redis.Client) {
    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")
    }
}

Notes:

Tip:

ExpireKeys Function

// ExpireKeys sets an expiration time for keys in Redis
func ExpireKeys(client *redis.Client) {
    var err error
    // Set a key with expiration time
    err = client.Set(ctx, "yooo", "I will expire soon!", 10*time.Second).Err()
    if err != nil {
        log.Fatal(err)
    }
}

Notes:

Tip:

subscripeChannel Function

// subscripeChannel demonstrates how to subscribe to a Redis Pub/Sub channel
func subscripeChannel(client *redis.Client) {
    pubsub := client.Subscribe(ctx, "mychannel")
    _, err := pubsub.Receive(ctx)
    if err != nil {
        log.Fatal(err)
    }
    ch := pubsub.Channel()
    for msg := range ch {
        fmt.Println("Received message:", msg.Payload)
    }
}

Notes:

Tip: