Details of the use of redis in Go language development

  • 2020-06-19 10:28:03
  • OfStack

Some time ago, I was busy with other things and Shared a little. Recently, I learned the application of redis in THE development of Go language.

1. Theoretical knowledge

Redis is an open source Key-ES11en database written in C language that supports network interaction and can be either memory based or persistent.

Redis advantage

The Redis can read 110,000 times /s and write 81,000 times /s.

Rich data types - Redis supports 2 base case Strings, Lists, Hashes, Sets and Ordered Sets data type operations.

All operations on Redis are atomic, and Redis supports the atomicity of several operations.

Rich features like Redis also support publish/subscribe, notifications, key expiration, and more.

How is Redis different from other ES43en-ES44en stores?

Redis has a more complex data structure and provides atomic manipulation of them, which is an evolutionary path different from other databases. Redis's data types are based on basic data structures that are transparent to the programmer without additional abstraction.

Redis runs in memory but can be persisted to disk, so there is a memory tradeoff when doing fast reads and writes to different data sets because the amount of data cannot be greater than hardware memory. Another advantage with in-memory databases is that it is very easy to operate in memory compared to the same complex data structures on disk, so Redis can do a lot of internally complex things. Also, in terms of disk formats they are compact and append because they do not need random access.

2. Use:

The open source library redis was used in the development process as follows

github address

https://github.com/garyburd/redigo

Document Address:

http://godoc.org/github.com/garyburd/redigo/redis

1. Database connection


func connDB() (c redis.Conn, err error) {
  db, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
    fmt.Println("Connect to redis error", err)
    return
  }
  return db, err
}

2, write


func saveToDB(c redis.Conn) {
  _, err := c.Do("SET", "name", "qiuqiu", "EX", "50")
  if err != nil {
    fmt.Println("redis set failed:", err)
  } else {
    fmt.Println("save success")
  }
}

// Batch write 
_, err := c.Do("MSET", "name", "superWang", "SEX", "F", "EX", "50")
  if err != nil {
    fmt.Println("redis set failed:", err)
  } else {
    fmt.Println("save success")
  }

//tips:EX Is the expiration time of the value 

3, read


func readFromDB(c redis.Conn) {
  username, err := redis.String(c.Do("GET", "name"))
  if err != nil {
    fmt.Println("redis get failed:", err)
  } else {
    fmt.Printf("Get mykey: %v \n", username)
  }

}
// Bulk read 
func readFromDB(c redis.Conn) {
  username, err := redis.Strings(c.Do("MGET", "SEX", "name"))
  if err != nil {
    fmt.Println("redis get failed:", err)
  } else {
    fmt.Printf("Get mykey: %v \n", username)
  }

}

4, delete,


func delFromDB(c redis.Conn) {
  _, err := c.Do("DEL", "name", "SEX")
  if err != nil {
    fmt.Println("redis delete failed:", err)
  } else {
    fmt.Println("delete success")
  }
}

5. Set keys expiration time

If the EX time is set at write time, the current key expiration time is set, and if it is not set, the current key lasts forever

6. Read and write json to redis


// write json
func saveJsonDataToDB(c redis.Conn) {
  imap := map[string]string{"name": "waiwaigo", "phone": "13498739038"}
  value, _ := json.Marshal(imap)
  n, err := c.Do("SETNX", "jsonkey", value)
  if err != nil {
    fmt.Println(err)
  }
  if n == int64(1) {
    fmt.Println("success")
  }
}

// read json
func readJsonFromDB(c redis.Conn) {
  var imapGet map[string]string
  valueGet, err := redis.Bytes(c.Do("GET", "jsonkey"))
  if err != nil {
    fmt.Println(err)
  }

  errShal := json.Unmarshal(valueGet, &imapGet)
  if errShal != nil {
    fmt.Println(err)
  }
  fmt.Println(imapGet["name"])
  fmt.Println(imapGet["phone"])
}

7. List operation, and store 1 group of data


// Save the list 
func saveListToDB(c redis.Conn) {
  _, err := c.Do("lpush", "username", "zhangsan")
  if err != nil {
    fmt.Println("redis set failed:", err)
  }

  _, err = c.Do("lpush", "username", "lisi")
  if err != nil {
    fmt.Println("redis set failed:", err)
  }
  _, err = c.Do("lpush", "username", "wangwu")
  if err != nil {
    fmt.Println("redis set failed:", err)
  }
}

// Read the list 
func readListFromDB(c redis.Conn) {
  values, _ := redis.Values(c.Do("lrange", "username", "0", "2"))
  fmt.Printf("count%d", len(values))
  for _, v := range values {
    fmt.Println(string(v.([]byte)))
  }
}

Related articles: