How to use Redis service in Golang

Keywords: Redis JSON github Windows

During development, if there is a need for caching, you may need to add a Redis block to the background. The core package is open-source
github.com/garyburd/redigo

This package provides the connection of redis service and encapsulates various command functions of redis
1. First, install redis service for the computer: https://godoc.org/github.com/garyburd/redigo/redis#pkg-variables
2. After installation, open cmd and execute redis-server.exe redis.windows.conf
If the command does not exist, you need to put the path of redis, that is, the directory where redis-server.exe is located, into the path in the environment variable

3. After execution, you can see the following figure, which indicates that the service is started

4. Write go file for access and operation
main.go

package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
    "time"
    "encoding/json"
)

func main() {

    //1. Connect to redis
    c, err := redis.Dial("tcp", "127.0.0.1:6379")
    if err != nil {
        fmt.Println("1.Connect redis fail", err)
        return
    }
    fmt.Println("1.Successful connection",c)
    defer c.Close()

    //2. Data reading and writing: SET command and GET command
    // 2.1 create a redis data object with key = user_name, value = ft, and write
    _, err = c.Do("MSET", "user_name", "ft")
    if err != nil {
        fmt.Println("Data setting failed:", err)
    }

    username, err := redis.String(c.Do("GET", "user_name"))

    if err != nil {
        fmt.Println("Data acquisition failed:", err)
    } else {
        fmt.Println("2.1.Obtain user_name",username)
    }
    // 2.2 write a content whose time limit is 5 seconds: EX command
    _, err = c.Do("SET", "user_name2", "ft2","EX", "5")
    if err != nil {
        fmt.Println("Data setting failed:", err)
    }

    //Not expired
    username2, err := redis.String(c.Do("GET", "user_name2"))
    if err != nil {
        fmt.Println("Data acquisition failed:", err)
    } else {
        fmt.Printf("2.2 Get unexpired user_name2: %v \n", username2)
    }
    //8 seconds delay, expired
    time.Sleep(8 * time.Second)
    username2, err = redis.String(c.Do("GET", "user_name2"))
    if err != nil {
        fmt.Println("2.2 Data acquisition failed after expiration:", err)
    } else {
        fmt.Printf("2.2 Failed to get expired after delay user_name2: %v \n", username2)
    }

    //2.3 batch write and batch write: MSET,MGET command
    _, err = c.Do("MSET", "user_name", "ft","class_name","UD01")
    if err != nil {
        fmt.Println("Batch data setting failed:", err)
    }

    results, err := redis.Strings(c.Do("MGET", "user_name","class_name"))

    if err != nil {
        fmt.Println("Data acquisition failed:", err)
    } else {
        fmt.Println("2.3 Batch obtained successfully",results)
    }

    //2.4 judge whether there is a key value pair
    If_Exit, err := redis.Bool(c.Do("EXISTS", "class_name"))
    if err != nil {
        fmt.Println("error:", err)
    } else {
        fmt.Printf("2.4 class_name Does it exist?: %v \n", If_Exit)
    }

    //3 delete key
    affectCount,err:=redis.Int(c.Do("DEL","class_name"))
    if err != nil {
        fmt.Println("error:", err)
    } else {
        fmt.Printf("3.class_name Deleted, rows affected: %v \n", affectCount)
    }

    //4 access json object: SETNX is equivalent to SET if not exist
    key := "jsonKey"
    imap := map[string]string{"username": "666", "phonenumber": "888"}
    value, _ := json.Marshal(imap)

    _,err = c.Do("SETNX", key, value)
    if err != nil {
        fmt.Println(err)
    }


    var result map[string]string

    buf, err := redis.Bytes(c.Do("GET", key))
    if err != nil {
        fmt.Println(err)
    }


    errShal := json.Unmarshal(buf, &result)
    if errShal != nil {
        fmt.Println(err)
    }
    fmt.Println("4.Obtain json Object success:userName",result["username"])
    fmt.Println("                 phonenumber",result["phonenumber"])

    //5. Set expiration time: EXPIRE
    _,err= c.Do("EXPIRE", key, 24*60*60)
    if err != nil {
        fmt.Println(err)
    }


    //6. The pipeline sends and receives according to the principle of queue first in first out
    c.Send("SET", "userId", "DF123")
    c.Send("GET", "userId")
    c.Flush()
    c.Receive() // reply from SET
    valueGet, errr := c.Receive() // reply from GET
    fmt.Println(redis.String(valueGet,errr))
}

Result:

1.Successful connection &{{0 0} 0 <nil> 0xc042064030 0 0xc0420362a0 0 0xc042040280 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]}
2.1.Obtainuser_name ft
2.2 Get unexpired user_name2: ft2 
2.2 Data acquisition failed after expiration: redigo: nil returned
2.3 Batch obtained successfully [ft UD01]
2.4 class_nameDoes it exist?: true 
3.class_nameDeleted, rows affected: 1 
4.ObtainjsonObject success:userName 666
                 phonenumber 888
bar <nil>

Posted by trilbyfish on Fri, 10 Apr 2020 08:36:20 -0700