SoFunction
Updated on 2025-03-01

Detailed explanation of the use of redis in Go language development

Some time ago, I was busy with other things and shared a little. I recently learned about the application of redis in Go language development.

1. Theoretical knowledge

Redis is an open source, written in C, network interaction-based, memory-based and persistent Key-Value database.

Redis Advantages

Extremely high performance – Redis can read at 110,000 times/s and write at 81,000 times/s.

Rich data types – Redis supports Strings, Lists, Hashes, Sets and Ordered Sets data type operations in binary cases.

Atomic – All operations of Redis are atomic, and Redis also supports atomic execution after the whole merge of several operations.

Rich features – Redis also supports publish/subscribe, notifications, key expiration and other features.

How is Redis different from other key-value storage?

Redis has more complex data structures and provides atomic operations on them, an evolutionary path different from other databases. Redis's data types are all based on basic data structures while being transparent to programmers without additional abstraction.

Redis runs in memory but can be persisted to disk, so it is necessary to weigh the memory when reading and writing different data sets at high speed, because the amount of data cannot be greater than the hardware memory. Another advantage in in-memory database is that it is very simple to operate in memory than the same complex data structures on disk, so Redis can do many internally complex things. At the same time, they are compact in the form of disk formats, as they do not require random access.

2. Use:

During the development process, we used the open source library redis as follows

github address

/garyburd/redigo

Document address:

//garyburd/redigo/redis

1. Database connection

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

2. Write

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

//Batch writing_, err := ("MSET", "name", "superWang", "SEX", "F", "EX", "50")
  if err != nil {
    ("redis set failed:", err)
  } else {
    ("save success")
  }

//tips:EX is the expiration time of this value

3. Read

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

}
//Batch readingfunc readFromDB(c ) {
  username, err := (("MGET", "SEX", "name"))
  if err != nil {
    ("redis get failed:", err)
  } else {
    ("Get mykey: %v \n", username)
  }

}

4. Delete

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

5. Set the keys expiration time

If the EX time is set during writing, the current key expiration time is the setting time. If it is not set, the current key is permanently valid

6. Read and write json to redis

//Write jsonfunc saveJsonDataToDB(c ) {
  imap := map[string]string{"name": "waiwaigo", "phone": "13498739038"}
  value, _ := (imap)
  n, err := ("SETNX", "jsonkey", value)
  if err != nil {
    (err)
  }
  if n == int64(1) {
    ("success")
  }
}

//Read jsonfunc readJsonFromDB(c ) {
  var imapGet map[string]string
  valueGet, err := (("GET", "jsonkey"))
  if err != nil {
    (err)
  }

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

7. List operation, store a set of data

//Save the listfunc saveListToDB(c ) {
  _, err := ("lpush", "username", "zhangsan")
  if err != nil {
    ("redis set failed:", err)
  }

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

//Read the listfunc readListFromDB(c ) {
  values, _ := (("lrange", "username", "0", "2"))
  ("count%d", len(values))
  for _, v := range values {
    (string(v.([]byte)))
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.