Example of a method to manipulate redis using go

  • 2020-07-21 08:20:25
  • OfStack

Redis brief introduction

Introduction to the

The discussion of Redis is a common topic in the background development, and it is also a basic research point for the interview of back-end development. The background and details of Redis will not be covered here. However described, the core of Redis is an in-memory ES9en-ES10en multi-data structure store that provides persistence services. The memory-based nature of Redis makes it a natural fit for high-concurrency data read/write cache optimization, but it also causes the problem of excessive memory overhead. Therefore, Redis is an unstoppable killer under certain circumstances, which deserves further study.

Install redis and run the following go code:


package main
import (
  "time"
  "fmt"
  "github.com/go-redis/redis"
)
var Client *redis.Client
func init() {
  Client = redis.NewClient(&redis.Options{
    Addr:     "127.0.0.1:6379",
    PoolSize:   1000,
    ReadTimeout: time.Millisecond * time.Duration(100),
    WriteTimeout: time.Millisecond * time.Duration(100),
    IdleTimeout: time.Second * time.Duration(60),
  })
  _, err := Client.Ping().Result()
  if err != nil {
    panic("init redis error")
  } else {
    fmt.Println("init redis ok")
  }
}
func get(key string) (string, bool) {
  r, err := Client.Get(key).Result()
  if err != nil {
    return "", false
  }
  return r, true
}
func set(key string, val string, expTime int32) {
  Client.Set(key, val, time.Duration(expTime) * time.Second)
}
func main() {
  set("name", "x", 100)
  s, b := get("name")
  fmt.Println(s, b)
}

Results:

[

init redis ok
x true

]

The expiration time is 100s. After expiration, get cannot get the information and returns nil

Simple, not much to say.

conclusion


Related articles: