1. redis 官方go驅(qū)動包下載
go get github.com/gomodule/redigo/redis
2. 測試
創(chuàng)建如下test.go測試文件,編譯并執(zhí)行。在redis中查找到鍵c1值為hello,說明安裝成功
package main
import ( "github.com/gomodule/redigo/redis")
func main(){
conn,_ := redis.Dial("tcp", ":6379")
defer conn.Close()
conn.Do("set", "c1", "hello")
}
備注: 此處默認設(shè)置ip及端口號為127.0.0.1 和 6379,可手動設(shè)置下代碼中的ip及port 。
conn,_ := redis.Dial("tcp", "ip:port")
3. 操作指令
Go操作redis文檔https://godoc.org/github.com/gomodule/redigo/redis
3.1連接數(shù)據(jù)庫
Dial(network, address string)(conn,err)
3.2 執(zhí)行數(shù)據(jù)庫操作命令
Send函數(shù)發(fā)出指令冰蘑,flush將連接的輸出緩沖區(qū)刷新到服務(wù)器,Receive接收服務(wù)器返回的數(shù)據(jù)
Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)
3.3另外一種執(zhí)行數(shù)據(jù)庫操作命令
Do(commandName string, args ...interface{}) (reply interface{}, err error)
3.4 reply helper functions(回復(fù)助手函數(shù))
Bool村缸,Int祠肥,Bytes,map梯皿,String仇箱,Strings和Values函數(shù)將回復(fù)轉(zhuǎn)換為特定類型的值县恕。為了方便地包含對連接Do和Receive方法的調(diào)用,這些函數(shù)采用了類型為error的第二個參數(shù)工碾。如果錯誤是非nil弱睦,則輔助函數(shù)返回錯誤入录。如果錯誤為nil温赔,則該函數(shù)將回復(fù)轉(zhuǎn)換為指定的類型:
exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
//處理錯誤代碼
}
reflect.TypeOf(exists)//打印exists類型
常用的回復(fù)助手函數(shù)
- func Bool(reply interface{}, err error) (bool, error)
- func ByteSlices(reply interface{}, err error) ([][]byte, error)
- func Bytes(reply interface{}, err error) ([]byte, error)
- func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
- func Float64(reply interface{}, err error) (float64, error)
- func Float64s(reply interface{}, err error) ([]float64, error)
- func Int(reply interface{}, err error) (int, error)
- func Int64(reply interface{}, err error) (int64, error)
- func Int64Map(result interface{}, err error) (map[string]int64, error)
- func Int64s(reply interface{}, err error) ([]int64, error)
- func IntMap(result interface{}, err error) (map[string]int, error)
- func Ints(reply interface{}, err error) ([]int, error)
3.5 Scan 函數(shù)
Scan函數(shù)從src復(fù)制到dest指向的值。
Dest參數(shù)的值必須是整數(shù)健无,浮點數(shù)旬迹,布爾值火惊,字符串,[]byte奔垦,interface{}或這些類型的切片屹耐。Scan使用標準的strconv包將批量字符串轉(zhuǎn)換為數(shù)字和布爾類型。
func Scan(src [] interface {},dest ... interface {})([] interface {},error)
示例代碼:
var value1 int
var value2 string
reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
if err != nil {
//處理錯誤代碼
}
if _, err := redis.Scan(reply, &value1, &value2); err != nil {
// 處理錯誤代碼
}