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.