美文网首页
Redis 学习笔记9 - 使用 redigo 访问 redis

Redis 学习笔记9 - 使用 redigo 访问 redis

作者: 张云飞Vir | 来源:发表于2020-03-31 18:32 被阅读0次

    0. 背景

    Redis 的 API 非常简单和易于编程。处理使用命令行工具来连接,也可以用你喜欢的语言,本文描述使用 Go 语言 通过 redigo 库连接。

    1.redigo 介绍

    redigo 是一个连接 Redis 数据库的客户端框架

    Github地址:https://github.com/gomodule/redigo

    它是被 redis 官方网站推荐的框架。

    2. 基本操作实例

    2.1 导入包 Import:

      import "github.com/gomodule/redigo/redis"
    

    2.2 连接

    Conn接口是使用Redis的主要接口。应用程序通过调用Dial 函数创建连接。当使用完后,必须调用connection Close方法。

    Dial函数

    c, err := redis.Dial("tcp", ":6379")
    if err != nil {
        // handle error
    }
    defer c.Close()
    

    2.3 Do 函数

    Do 很通用,它用来执行指令。

     _, err = conn.Do("Set", "name", "tomjerry")
        if err != nil {
            fmt.Println("set err=", err)
            return
        }
     
        r, err := redis.String(conn.Do("Get", "name"))
        if err != nil {
            fmt.Println("set err=", err)
            return
        }
    

    2.4 操作 reids 中的 string 结构

    // 操作 reids 中的 string 结构
        c.Do("SET", "hello", "world")
        s, _ := redis.String(c.Do("GET", "hello"))
    
        fmt.Printf("%#v\n", s)
    
        
    

    2.5 操作 hash结构

    // 操作 hash结构,HMSET 一次写入多个属性值
        m := map[string]string{
            "title":  "Example2",
            "author": "Steve",
            "body":   "Map",
        }
    
        if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
            fmt.Println(err)
            return
        }
    

    2.6 管道

    c.Send("SET", "foo", "bar")
    c.Send("GET", "foo")
    c.Flush()
    c.Receive() // reply from SET
    v, err = c.Receive() // reply from GET
    

    2.7 发布和订阅 Publish and Subscribe

    使用Send、Flush和Receive方法实现发布/订阅服务器。

    c.Send("SUBSCRIBE", "example")
    c.Flush()
    for {
        reply, err := c.Receive()
        if err != nil {
            return err
        }
        // process pushed message
    }
    

    2.7 处理响应的一些辅助方法

    可以使用 redis.Bool、redis.Int、redis.Bytes、redis.String、redis.Strings和redis.Values函数 帮助把应答内容转换为特定类型的值。

    
    exists, err := redis.Bool(c.Do("EXISTS", "foo"))
    if err != nil {
        // handle error return from c.Do or type conversion error.
    }
    
    

    Scan函数转换 返回的数组元素 到 Go 的数据类型

    
    var value1 int
    var value2 string
    reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
    if err != nil {
        // handle error
    }
     if _, err := redis.Scan(reply, &value1, &value2); err != nil {
        // handle error
    }
    ```
    
    # 3. 连接池
    
    **连接池 Pool的使用**
    应用程序调用Get方法从池中获取连接,调用连接的Close方法将连接的资源返回到池。
    
    连接池 是常用的建立连接的方式。
    
    ```
    
    func newPool(addr string, password string) *redis.Pool {
        return &redis.Pool{
            MaxIdle:     3,
            IdleTimeout: 240 * time.Second,
            // Dial or DialContext must be set. When both are set, DialContext takes precedence over Dial.
            Dial: func() (redis.Conn, error) { return redis.Dial("tcp", addr, redis.DialPassword(password)) },
        }
    }
    
    var (
        pool *redis.Pool
    )
    
    func initPool() {
        redisServer := "dev.com:6379"
        password := "123456"
        pool = newPool(redisServer, password)
        // 执行操作
    
        c := pool.Get()
        defer c.Close()
    
        // 操作 reids 中的 string 结构
        c.Do("SET", "hello", "world")
    }
    ```
    
    # 4. 参考
    
    [https://github.com/gomodule/redigo](https://github.com/gomodule/redigo)
    
    [https://godoc.org/github.com/gomodule/redigo/redis#pkg-examples](https://godoc.org/github.com/gomodule/redigo/redis#pkg-examples)
    
    
    END

    相关文章

      网友评论

          本文标题:Redis 学习笔记9 - 使用 redigo 访问 redis

          本文链接:https://www.haomeiwen.com/subject/terguhtx.html