// 它通常由main函数、初始化和测试使用,并作为传入请求的顶级上下文 ctx := context.Background() _, err = rdb.Ping(ctx).Result() if err != nil { return err } return nil } func redisSetKey(key string, val string) error
})// 创建一个Context,并设置超时时间ctx,cancel:=context.WithTimeout(context.Background(),2*time.Second)defercancel()// 尝试向Redis写入数据err:=rdb.Set(ctx,"key","value",0).Err()iferr!
type Options struct { // 网络类型:[ tcp , unix ] // 默认是 tcp Network string // host:port 地址 Addr string // 要使用的 TLS 配置。 当设置 TLS 时将协商。 TLSConfig *tls.Config //创建一个新的连接,优先于Newwork和Addr选项 Dialer func(ctx context.Context, network, addr...
packagemainimport("context""fmt""github.com/go-redis/redis/v8")funcmain(){// 创建Redis客户端client:=redis.NewClient(&redis.Options{Addr:"localhost:6379",// Redis服务器地址Password:"",// 密码,如果没有密码则为空字符串DB:0,// 使用的数据库编号})// Ping测试连接pong,err:=client.Ping(contex...
ctx = context.Background()// 设置 key 的值,0 表示永不过期err = rdb.Set(ctx,"setkey-1","value-1",0).Err()iferr !=nil{panic(err) }// 设置 key 的值的过期时间为 30 秒err = rdb.Set(ctx,"setkey-2","value-2", time.Second*30).Err()iferr !=nil{panic(err) ...
=nil{returnerr}}retryTimeout:=true// 在获取到连接的基础上进行后续操作(注意,获取连接的方法被封装成了withConn)lastErr=c.withConn(ctx,func(ctx context.Context,cn*pool.Conn)error{// 向网络连接buffer中写入数据err:=cn.WithWriter(ctx,c.opt.WriteTimeout,func(wr*proto.Writer)error{returnwriteCmd(...
// go-redis/redis/v8@v8.11.5/internal/pool/pool.go // 用完把链接放进链接池 func (p *ConnPool) Put(ctx context.Context, cn *Conn) { if cn.rd.Buffered() > 0 { internal.Logger.Printf(ctx, "Conn has unread data") p.Remove(ctx, cn, BadConnError{}) return } if !cn.pooled {...
= config.GetConnect().HSet(context.Background(), "hash", []string{"key3", "value3", "key4", "value4"}).Result()// 使用maphasMap:=make(map[string]string)hasMap["key5"]="value5"hasMap["key6"]="value6"result,err:=config.GetConnect().HSet(context.Background(),"hash",hasMap...
"context" "fmt" "time" "/go-redis/redis/v8"// 注意导入的是新版本 ) var( rdb*redis.Client ) // 初始化连接 funcinitClient() (errerror) { rdb=redis.NewClient(&redis.Options{ Addr:"localhost:16379", Password:"",// no password set ...
首先,确保你的 Go 环境已经开启了模块支持,并使用以下命令初始化和安装 go-redis:go mod init github.com/my/repogo get github.com/redis/go-redis/v9 下面是一个快速开始的示例,演示了如何在 Go 应用中使用 go-redis 连接 Redis 并执行简单的 SET 和 GET 操作:import ( "context" "fmt" ...