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
- This example demonstrates how to use the Go Redis client (
go-redis
) to
interact with a Redis server. It covers basic operations such as setting/getting
values, working with lists, handling errors, setting expiration for keys,
and subscribing to a Redis channel.
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:
- The Set() function stores a key-value pair in Redis. The third argument
is the expiration time (0 means no expiration). - The Get() function retrieves the value of a given key from Redis.
Tip:
- Always check for errors after interacting with Redis, as network issues
or Redis server downtime can lead to failed operations.
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:
- LPush inserts elements at the head (left) of the list, while RPush adds
them to the tail (right). - LRange retrieves elements from a list based on index; 0 means start,
and -1 means the end of the list. - LPop and RPop remove elements from the head and tail of the list,
respectively.
Tip:
- Use Del() to delete the entire list if needed.
- When working with lists, LRANGE is essential for retrieving specific
segments or all elements.
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:
- This function demonstrates error handling when retrieving a key.
It checks if the key doesn't exist (redis.Nil), if there's an error,
or if the value is empty.
Tip:
- Always handle different error scenarios
(e.g., missing keys or failed network connections) to avoid crashes.
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:
- The Set() function allows setting a key with an expiration time. In this case,
"yooo" will expire in 10 seconds.
Tip:
- Use expiration for cache data that becomes stale or unnecessary
after a specific period.
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:
- The subscripeChannel() function listens for messages on the mychannel
channel. When a message is published, it prints the payload.
Tip:
-
Use Pub/Sub to build real-time messaging systems like notifications
or chat applications.continue:[[]]
before:go-bycript.md