【Go - redis client 单例】

2024-07-28  本文已影响0人  wn777

以下是redis client单例,使用sync.Once保证无论单线程(协程)还是多线程(协程) 只执行一次。

示例

package main

import (
    "context"
    "fmt"
    "sync"

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

var (
    RedisClientSingleton *redis.Client
    once                 sync.Once
)

func getRedisClientSingleton() *redis.Client {
    once.Do(func() {
        rdb := redis.NewClient(&redis.Options{
            Addr:     "",
            Password: "", // no password set
            DB:       0,             // use default DB
        })
        RedisClientSingleton = rdb
    })
    return RedisClientSingleton
}

func main() {

    rdb := getRedisClientSingleton()
    var ctx = context.Background()
    val, err := rdb.Get(ctx, "key1").Result()
    if err == redis.Nil {
        fmt.Println("key1 does not exist")
    } else if err != nil {
        panic(err)
    } else {
        fmt.Println("key1", val)
    }

    rdb2 := getRedisClientSingleton()

    if rdb == rdb2 {
        fmt.Println("rdb and rdb2 are the same")
    }

}

上一篇 下一篇

猜你喜欢

热点阅读