Installation
go get github.com/gomodule/redigo/redis
After the installation is complete, you can create a go file yourself: test.go
The content is as follows:
package main
import "github.com/gomodule/redigo/redis"
func main(){
conn, _ := redis.Dial("tcp", ":6379")
defer conn.Close()
conn.Do("set", "c1", "hello")
}
Then compile and run the file, and then if the value of the key "c1" is found in redis, the installation is successful.
Method of operation
Go Redis documentation:
https://godoc.org/github.com/gomodule/redigo/redis
Connect to the database
Dial(network, address string) (conn, err)
example:
redis.Dial("tcp", ":6379")
Execute database operation commands
Send(commandName string, args ...interface{} error
Flush() error
Receive() (reply interface{}, err error)
The Send function issues an instruction, Flush flushes the connected output buffer to the server, and Receive receives the data returned by the server
example:
conn.Send("SET", "foo", "bar")
conn.Send("GET", "foo")
conn.Flush() // send the buffer command to the server
conn.Receive() // Receive the data returned by the set request
v, err := conn.Receive() // Receive the data requested by get
Another command to perform database operations (commonly used)
Do(commandName string, args ...interface{}) (reply interface{}, err error)
Reply helper functions
Bool, Int, Bytes, map, String, Strings and Values functions convert the response to a specific type of value.
In order to conveniently include calls to connect the Do and Receive methods, these functions take a second parameter of type error. If the error is non-nil, the helper function returns an error. If the error is nil, the function converts the reply to the specified type:
exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
//Handle the error code
}
reflect.TypeOf(exists) //Print exists type
Scan function
func Scan(src [] interface {},dest ... interface {}) ([] interface {},error)
The Scan function copies from src to the value pointed to by dest.
The value of the Dest parameter must be an integer, floating-point number, boolean, string, []byte, interface{} or a slice of these types. Scan uses the standard strconv package to convert batch strings to numeric and boolean types.
example:
var value1 int
var value2 string
reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
if err != nil {
//Handle the error code
}
if _, err := redis.Scan(reply, &value1, &value2); err != nil {
// Handling error codes
}
Combine with the project
Serialization and deserialization
Serialization (byteization)
var buffer bytes.Buffer // container
enc := gob.NewEncoder(buffer) // encoder
err := enc.Encode(dest) // Encoding
Deserialization (deserialization)
dec := gob.NewDecoder(bytes.NewReader(buffer.bytes())) // decoder
dec.Decode(src) // Decode
For more Go article See:
Go Language Tutorial
Go_Lang_Gin_Framework_Middleware
Top comments (0)