Operating redis in go language

Keywords: PHP Redis github Database git

To use redis in go language, you need to download the official redis toolkit.

Execute in the go path path: go get github.com/garden/redis/redis
If git is not installed, you can download a zip package from the following link, and then unzip it to the local gopath path path.

If you don't know the path of gopath, look at the configuration parameters of environment variables, which are generally visible.

Of course, there are more than one redis tool. Here are not all examples. In fact, the most important thing is your understanding of the basis and command of redis.
redis official document address: http://redisdoc.com/string/index.html

A simple example

package main

import (
    "fmt"

    "github.com/garyburd/redigo/redis"
)

func string() {
    //Write and read data to redis through go
    //1. Link to go
    conn, err := redis.Dial("tcp", "127.0.0.1:6379")
    if err != nil {
        fmt.Println("reis connect err=", err)
        return
    }
    defer conn.Close()
    //2. Write data string [Key Val] to redis through go
    _, err = conn.Do("Set", "name", "tom cat")
    if err != nil {
        fmt.Printf("Set err=%v \n", err)
    }

    //3. Read data from redis

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

    //name, ok := r.(string)
    fmt.Println("name:", r)
}

func main() {
    //In fact, it's all about using the command of redis skillfully.
    //fixme redis document address: http://redisdoc.com/string/index.html
    //string()
    //hash()
    //list()
    subscribe()
}
func subscribe() {
    c, err := redis.Dial("tcp", "127.0.0.1:6379")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer c.Close()

    psc := redis.PubSubConn{c}
    psc.Subscribe("redChatRoom")
    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
        case error:
            fmt.Println(v)
            return
        }
    }
}

func list() {
    //1. Connect to the redis database
    conn,err :=redis.Dial("tcp","127.0.0.1:6379")
    if err != nil{
        fmt.Println("redis connection failed,Error message:",err)
        return
    }
    defer conn.Close()
    fmt.Println("redis Successful connection")

    //_, err = conn.Do("LPush", "heroList", "songjiang", 23, "long", 29)
    //if err != nil {
    //  fmt.Println(err)
    //  return
    //}
    //fmt.Println("LPush success")


    //values, _ := redis.Values(conn.Do("lrange", "heroList", "0", "100"))
    str, err := redis.String(conn.Do("RPop", "heroList"))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(str)
    //for _, v := range values {
    //  fmt.Println(v)
    //}

    // perhaps
    //var v1 string
    //redis.Scan(values, &v1)
    //fmt.Println(v1)
}

func hash() {
    ////Write and read data to redis through go
    ////1. Link to go
    //conn, err := redis.Dial("tcp", "127.0.0.1:6379")
    //if err != nil {
    //  fmt.Println("reis connect err=", err)
    //  return
    //}
    //fmt.Println("-----------")
    //
    //defer conn.Close()
    //2. Write data string [Key Val] to redis through go
    //_, err = conn.Do("HSet", "user", "name", "john")
    //if err != nil {
    //  fmt.Printf("Set err=%v \n", err)
    //}
    //_, err = conn.Do("HSet", "user", "age", 18)
    //if err != nil {
    //  fmt.Printf("Set err=%v \n", err)
    //}
    //_, err = conn.Do("HSet", "user", "gender", "boy")
    //if err != nil {
    //  fmt.Printf("Set err=%v \n", err)
    //}
    //
    ////3. Read data from redis
    //
    //r, err := redis.String(conn.Do("HGet", "user", "name"))
    //if err != nil {
    //  fmt.Println("get err=", err)
    //  return
    //}
    //
    ////name, ok := r.(string)
    //fmt.Println("name:", r)

    /*
    Batch operation
     */
    //1. Connect to the redis database
    con,err :=redis.Dial("tcp","127.0.0.1:6379")
    if err != nil{
        fmt.Println("redis connection failed,Error message:",err)
        return
    }
    defer con.Close()
    fmt.Println("redis Successful connection")

    //2. Write data to redis through go
    _,err = con.Do("HMSet","user2","name","Bob rice","age","19")
    if err != nil{
        fmt.Println("hmset Error, error message:",err)
        return
    }

    fmt.Println("hmset ok")

    //3. Read data to redis through go
    reply,err := redis.Strings(con.Do("HMGet","user2","name","age"))
    if err != nil{
        fmt.Println("hmget Error, error message:",err)
        return
    }
    fmt.Println("hmget ok")

    for i,v := range reply{
        fmt.Printf("[%d]=%s\t",i,v)
    }

}

Creation of redis connection pool

package main

import (
    "fmt"
    
    "github.com/garyburd/redigo/redis"
)

var pool *redis.Pool
func init()  {
    pool = &redis.Pool{
        MaxIdle:8,// Maximum free link
        MaxActive:0,// Represents the maximum number of connections to the database
        IdleTimeout:100,// Maximum idle time
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", "localhost:6379")
        },
    }
}

func main() {
    //Take a link from the pool first
    conn := pool.Get()
    defer conn.Close()

    //
    _, err := conn.Do("Set", "name", "hiram~")
    if err != nil {
        fmt.Println(err)
        return
    }

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

}

Posted by launchcode on Sat, 19 Oct 2019 13:55:57 -0700