Use Hmset to replace hset in go to improve the access efficiency of Redis and the problems that may be encountered by concurrency Goroutine

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

It is less efficient to use Hset to deposit data directly into Redis, and when the data to be deposited is known, it can be hmset to replace hset for storage.

var args []Interface{}{"Myhash"} for Key, Value := Range FVs {    args = Append(args, Key, value)}_, Err := Conn. Do("Hmset", args...)

Note: FVs is the map map for the corresponding Key,value, and the mapping is stored in the domain named Myhash in Redis. Represents all the elements in the order of the args slice.


Hmset storage speed is relatively hset fast, but using go goroutine concurrency Hmset can achieve better storage effect? The answer is in the negative.

When using multiple (10) Goroutine for concurrent hmset, such as

For i:=0;i<10;i++{   go func () {    ...        _, Err = conn. Do ("Hmset", args ...)        If err! = Nil {              FMT. PRINTLN (Err)         }    ...   }


The error will appear: Use of closed network connection

Cause of error: When Hmset writes to Redis, it can only have one write operation for a hash table and not multiple writes at the same time.

Workaround:

Lock before executing the hmset command, then unlock after execution. The solution for this example is as follows:

Import "Sync" var l sync. Mutexfor i:=0;i<10;i++{   go func () {    ...       L.lock ()        _, Err = conn. Do ("Hmset", args ...)        If err! = Nil {              FMT. PRINTLN (Err)         }      l.unlock () ...   }}


The use of the lock method ensures that only one hmset is written to Redis at a time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.