Redis 简单实践 | 青训营

79 阅读2分钟

Redis使用实践

创建Redis连接

导入依赖 go get github.com/redis/go-redis/v9

连接Redis-server

client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379", // ip : 端口
        Password: "", //密码
        DB:       1, //选择的数据库,Redis默认有 0 ~ 15 共16个数据库
    })

使用最简单的Context,源码中的描述是: Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

    ctx := context.Background()

接下来就可以使用Go语言程序操作Redis数据库了

首先引用官方文档的例子:

err := client.Set(ctx, "foo", "bar", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := client.Get(ctx, "foo").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("foo", val)

输出结果为 :foo bar

解读代码以上代码就可以基本窥见Redis的操作方法了,client.Set()方法用于设置键值对,四个参数分别是context对象,键,值和什么?答案是expiration。设置为0时,相当于永久储存。Set函数将把键值对的存活时间设置为KeepTTL(在源码中KeepTTL = -1。其作用相当于redis命令 set foo bar。那如果我们想要设置它的存活时间呢?可以使用类似这样的语句 :\


err := client.Set(ctx, "foo", "bar", 10*time.Second).Err()

也就是将0改为 10 * time.Second(当然有其他单位,想用什么都可以),这样就可以将键值对的存活时间设置为10秒了。

查询操作使用Get()方法,再用Result取出返回值,两个参数分别为context和键,很简单。找到了返回值会被赋给val,那如果没有找到呢?这时候两个返回参数中的err就会发挥作用了,当err为nil的时候说明我们找到了这个值,如果err不为nil,且err的内容为“redis :nil”,就说明这个键值对并不存在,非常简单易懂。