Golang Getting Started Series 7: Use of redis

The previous talk is about some basic knowledge of the Go language. If you are interested, you can take a look at the previous article. http://quickintro123.com/index.php/category/golang/

Let's talk about how to use Redis in go today.
 

Installation

  1. The installation of Redis is very simple. I use the windows version directly for testing. How to install will not go into details. Want to know can read the previous article: https://quickintro123.com/index.php/2019/03/02/golang-entry-series-1-go-environment-construction/
     
  2. golang client, using go-redis,
  • go get github.com/go-redis
  • Then import this package in the code:
import "github.com/go-redis/redis"

Basic operation

Create Redis Connection Client

You can create a redis client through the redis.NewClient function. This method receives a redis.Options object parameter. Through this parameter, we can configure redis-related properties, such as the redis server address, database name, database password, and so on.
// create redis client

func GetRedisClient() *Client {
    redisdb := NewClient(&Options{
        Addr:     "127.0.0.1:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}

Cient.Ping () to check if you have successfully connected to the redis server

String operation

  • Set (key, value): assign a value to the string named key in the database valueget (key): return the value of the string named key in the database
  • GetSet (key, value): assign the last value to the string named key
  • MGet (key1, key2,…, key N): Returns the value of multiple strings in the library
  • SetNX (key, value): add string, name is key, value is value
  • SetXX (key, time, value): add string to the library, set the expiration time time
  • MSet (key N, value N): set multiple string values in batches
  • MSetNX (key N, value N): if all strings named key i do not exist
  • Incr (key): Increment 1 by the string named key
  • Incrby (key, integer): add integer to the string named key
  • Decr (key): subtract 1 from the string named key
  • Decrby (key, integer): reduce the integer for the string named key
  • Append (key, value): The value of the string named key is appended with valuesubstr (key, start, end): Returns the substring of the value of the string named key
func StringDemo() {
    fmt.Println("-----------------------welcome to StringDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient ==nil{
        fmt.Errorf("StringDemo redisClient is nil")
        return
    }

    name := "Jack"
    key :="name:Jack"
    redisClient.Set(key , name,1 * time.Second)
    val := redisClient.Get(key)
    if val == nil {
        fmt.Errorf("StringDemo get error")
    }
    fmt.Println("name", val)
}

List operation

  • RPush (key, value): Add a value element to the end of the list named key
  • LPush (key, value): add a value element to the head of the list named key
  • LLen (key): Returns the length of the list named key
  • LRange (key, start, end): Returns the elements in the list named key from start to end
  • LTrim (key, start, end): intercept the list named key
  • LIndex (key, index): Returns the element at index position in the list named key
  • LSet (key, index, value): assign a value to the element at index position in the list named key
  • LRem (key, count, value): delete the value element from the list of count keys
  • LPop (key): return and delete the first element in the list named key
  • RPop (key): return and delete the tail element in the list named key
  • BLPop (key1, key2, ... key N, timeout): The block version of the lpop command.
  • BRPop (key1, key2, ... key N, timeout): Block version of rpop.
  • RPopLPush (srckey, dstkey): Returns and deletes the tail element of the list named srckey, and adds this element to the head of the list named dstkey
func ListDemo(){
    fmt.Println("-----------------------welcome to ListDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("ListDemo redisClient is nil")
        return
    }
    articleKey := "article"
    result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    result,err = redisClient.LPush(articleKey, "d").Result() //
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    length, err := redisClient.LLen(articleKey).Result()
    if err != nil {
        fmt.Println("ListDemo LLen is nil")
    }
    fmt.Println("length: ", length) 

    mapOut,err1:=redisClient.LRange(articleKey,0,100).Result()
    if err1!=nil {
        fmt.Println(err1)
        return
    }
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
}

Hash operations

  • HSet (key, field, value): add element field to the hash named key
  • GetHGet (key, field): Returns the value corresponding to the field in the hash named key
  • HMget (key, (fields)): returns the value corresponding to field i in the hash named key
  • HMset (key, (fields)): add element field to the hash named key
  • InHIncrby (key, field, integer): increase the value of field in the hash named key by integer
  • HExists (key, field): Whether a field with key field exists in the hash named key
  • HDel (key, field): delete the field whose key is field in the hash named key
  • HLen (key): Returns the number of elements in the hash named key
  • KeyHKeys (key): Returns all keys in the hash named key
  • ValHVals (key): Returns the value corresponding to all keys in the hash named key
  • HGetall (key): Returns all keys (field) in the hash named key and their corresponding values
func HashDemo() {
    fmt.Println("-----------------------welcome to HashDemo-----------------------")
    redisClient := GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("HashDemo redisClient is nil")
        return
    }
    article := Article{18, "test22222", "test22222test22222test22222", 10, 0}
    articleKey := "article:18"

    redisClient.HMSet(articleKey, ToStringDictionary(&article))
    mapOut := redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    redisClient.HSet(articleKey, "Content", "test")
    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    view, err := redisClient.HIncrBy(articleKey, "Views", 1).Result()
    if err != nil {
        fmt.Printf("\n HIncrBy error=%s ", err)
    } else {
        fmt.Printf("\n HIncrBy Views=%d ", view)
    }
    fmt.Print("\n")

    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

}

connection pool

go-redis has implemented redis connection pool management, so we don't need to manually manage redis connections by ourselves.

By default, the connection pool size is 10. You can set the size of the redis connection pool to 5 through the PoolSize property of redis.Options.

func GetRedisClientPool() *Client{
    redisdb := NewClient(&Options{
        Addr: "127.0.0.1:6379",
        Password: "",
        DB: 0,
        PoolSize: 5,})

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}
// test
func connectPoolTest() {
    fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
    client :=GetRedisClientPool()
    wg := sync.WaitGroup{}
    wg.Add(10)

    for i := 0; i < 10; i++ {
        go func() {
            defer wg.Done()

            for j := 0; j < 1000; j++ {
                client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), 0).Err()
                client.Get(fmt.Sprintf("name%d", j)).Result()
            }

            fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
        }()
    }

    wg.Wait()
}

Complete code

package main

import (
    "fmt"
    . "github.com/go-redis/redis"
    . "redisDemo/models"
    "time"
    "sync"
)

func main() {
    fmt.Println("-----------------------welcome to redisdemo-----------------------")
    //StringDemo()
    //ListDemo()
    //HashDemo()
    connectPoolTest()
}

func StringDemo() {
    fmt.Println("-----------------------welcome to StringDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient ==nil{
        fmt.Errorf("StringDemo redisClient is nil")
        return
    }

    name := "Jack"
    key :="name:Jack"
    redisClient.Set(key , name,1 * time.Second)
    val := redisClient.Get(key)
    if val == nil {
        fmt.Errorf("StringDemo get error")
    }
    fmt.Println("name", val)
}

func ListDemo(){
    fmt.Println("-----------------------welcome to ListDemo-----------------------")
    redisClient:=GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("ListDemo redisClient is nil")
        return
    }
    articleKey := "article"
    result,err:=redisClient.RPush(articleKey, "a","b","c").Result() //Add an element with value to the end of the list named key
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    result,err = redisClient.LPush(articleKey, "d").Result() //Add a value element to the head of the list named key
    if err!=nil {
        fmt.Println(err)
        return
    }
    fmt.Println("result:",result)

    length, err := redisClient.LLen(articleKey).Result()
    if err != nil {
        fmt.Println("ListDemo LLen is nil")
    }
    fmt.Println("length: ", length) 

    mapOut,err1:=redisClient.LRange(articleKey,0,100).Result()
    if err1!=nil {
        fmt.Println(err1)
        return
    }
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
}

func HashDemo() {
    fmt.Println("-----------------------welcome to HashDemo-----------------------")
    redisClient := GetRedisClient()
    if redisClient == nil {
        fmt.Errorf("HashDemo redisClient is nil")
        return
    }
    article := Article{18, "test22222", "test22222test22222test22222", 10, 0}
    articleKey := "article:18"

    redisClient.HMSet(articleKey, ToStringDictionary(&article))
    mapOut := redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    redisClient.HSet(articleKey, "Content", "test")
    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

    view, err := redisClient.HIncrBy(articleKey, "Views", 1).Result()
    if err != nil {
        fmt.Printf("\n HIncrBy error=%s ", err)
    } else {
        fmt.Printf("\n HIncrBy Views=%d ", view)
    }
    fmt.Print("\n")

    mapOut = redisClient.HGetAll(articleKey).Val()
    for inx, item := range mapOut {
        fmt.Printf("\n %s:%s", inx, item)
    }
    fmt.Print("\n")

}

func GetRedisClient() *Client {
    redisdb := NewClient(&Options{
        Addr:     "127.0.0.1:6379",
        Password: "", // no password set
        DB:       0,                 // use default DB
    })

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}

func GetRedisClientPool() *Client{
    redisdb := NewClient(&Options{
        Addr: "127.0.0.1:6379",
        Password: "",
        DB: 0,
        PoolSize: 5,})

    pong, err := redisdb.Ping().Result()
    if err != nil {
        fmt.Println(pong, err)
    }
    return redisdb
}

// test
func connectPoolTest() {
    fmt.Println("-----------------------welcome to connect Pool Test-----------------------")
    client :=GetRedisClientPool()
    wg := sync.WaitGroup{}
    wg.Add(10)

    for i := 0; i < 10; i++ {
        go func() {
            defer wg.Done()

            for j := 0; j < 1000; j++ {
                client.Set(fmt.Sprintf("name%d", j), fmt.Sprintf("xys%d", j), 0).Err()
                client.Get(fmt.Sprintf("name%d", j)).Result()
            }

            fmt.Printf("PoolStats, TotalConns: %d, IdleConns: %d\n", client.PoolStats().TotalConns, client.PoolStats().IdleConns);
        }()
    }

    wg.Wait()
}

At last

Go language is very simple to use Redis, the basic usage of Redis has been covered above. You can try it yourself.

This entry was posted in development, golang and tagged , , . Bookmark the permalink.

107 Responses to Golang Getting Started Series 7: Use of redis

  1. Like!! I blog quite often and I genuinely thank you for your information. The article has truly peaked my interest.

  2. hedgchasp says:

    cash payday [url=http://payloanrgo.com/]advance cash[/url] instant cash loan cash fast cash loan network

  3. What i don’t realize is in truth how you are now not really
    a lot more smartly-appreciated than you might be now.
    You’re very intelligent. You realize therefore considerably with regards to this subject, produced me individually imagine it from numerous varied angles.
    Its like men and women aren’t involved until it is one thing to do with Woman gaga!
    Your individual stuffs excellent. All the time take care of it up!

  4. Hi there! I could have sworn I?ve visited your blog before but
    after browsing through some of the posts I realized it?s new to me.
    Anyhow, I?m definitely happy I discovered it and I?ll be bookmarking it and checking
    back often!

  5. I gotta bookmark this internet site it seems invaluable very helpful.

  6. Its such as you read my thoughts! You seem to understand so much
    about this, such as you wrote the e book in it or
    something. I think that you simply could do with some % to force the
    message home a little bit, but other than that, that is fantastic blog.
    A fantastic read. I will definitely be back.

  7. Great post however I was wondering if you could write a litte
    more on this topic? I’d be very thankful if you could elaborate a little bit further.
    Thanks!

  8. MaryCog says:

    [url=http://doxycycline1000.com/]doxycycline 100 mg tablet[/url] [url=http://propecia2020.com/]propecia no prescription[/url] [url=http://sildenafilrem.com/]sildenafil 20 mg[/url] [url=http://azithromycinzpak.com/]azithromycin 250 mg price[/url] [url=http://allopurinolzyl.com/]allopurinol price canada[/url] [url=http://lisinopriltbf.com/]lisinopril 12.5 tablet[/url] [url=http://levitra360.com/]generic levitra 20mg pills[/url] [url=http://ventolin2020.com/]ventolin tablets australia[/url] [url=http://metformin2.com/]metformin 500 mg pill[/url] [url=http://lisinopriltabs.com/]lisinopril generic[/url]

  9. Well I truly enjoyed reading it. This information procured by you is very practical for good planning.

  10. Thanks for sharing such a fastidious opinion, paragraph is good, thats why i
    have read it fully

  11. Heya i’m for the first time here. I found this board and I find It really useful & it
    helped me out much. I hope to give something back and help
    others like you helped me.

  12. I’m curious to find out what blog system you’re using?
    I’m having some minor security problems with my latest website and I’d like to find something more safeguarded.
    Do you have any solutions?

  13. JoeCog says:

    [url=https://motilium24.com/]motilium tablet uk[/url] [url=https://ventolin2020.com/]where can i buy ventolin over the counter[/url] [url=https://propecia1000.com/]can you buy propecia online[/url] [url=https://allopurinol365.com/]allopurinol cost[/url] [url=https://doxycycline1000.com/]vibramycin 100mg[/url] [url=https://retinarem.com/]retin a 0.025[/url] [url=https://fluoxetinetb.com/]fluoxetine capsules 10 mg[/url] [url=https://prednisolonester.com/]prednisolone 1[/url]

Leave a Reply

Your email address will not be published. Required fields are marked *