1. 程式人生 > 實用技巧 >Redis Go語言與Redis資料庫互動

Redis Go語言與Redis資料庫互動

安裝

go get github.com/gomodule/redigo/redis

安裝完成後,可以自己建立一個 go 檔案:test.go

內容如下:

package main

import "github.com/gomodule/redigo/redis"

func main(){
    conn, _ := redis.Dial("tcp", ":6379")
    defer conn.Close()
    conn.Do("set", "c1", "hello")
}

然後編譯執行該檔案,之後如果在 redis 中查詢到鍵 “c1” 的值為 “hello”,說明安裝成功。

操作方法

Go 操作 Redis 文件:https://godoc.org/github.com/gomodule/redigo/redis

連線資料庫

Dial(network, address string) (conn, err)

例:

redis.Dial("tcp", ":6379")

執行資料庫操作命令

	Send(commandName string, args ...interface{} error
    Flush() error
    Receive() (reply interface{}, err error)

Send 函式發出指令, Flush 將連線的輸出緩衝區重新整理到伺服器,Receive 接收伺服器返回的資料

例:

conn.Send("SET", "foo", "bar")
conn.Send("GET", "foo")
conn.Flush()  // 把緩衝區命令發到伺服器
conn.Receive()  // 接收 set 請求返回的資料
v, err := conn.Receive()  // 接收 get 請求傳輸的資料

另一種執行資料庫操作命令(常用)

Do(commandName string, args ...interface{}) (reply interface{}, err error)

reply helper functions (回覆助手函式)

Bool,Int,Bytes,map,String,Strings 和 Values 函式將回復轉換為特定型別的值。

為了方便地包含對連線 Do 和 Receive 方法的呼叫,這些函式採用了型別為 error 的第二個引數。如果錯誤是非 nil,則輔助函式返回錯誤。如果錯誤為 nil,則該函式將回復轉換為指定的型別:

exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
	//處理錯誤程式碼
}
reflect.TypeOf(exists)  //列印exists型別

Scan 函式

func Scan(src [] interface {},dest ... interface {}) ([] interface {},error)

Scan 函式從 src 複製到 dest 指向的值。

Dest 引數的值必須是整數,浮點數,布林值,字串,[]byte,interface{} 或這些型別的切片。Scan 使用標準的 strconv 包將批量字串轉換為數字和布林型別。

例:

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 {
    // 處理錯誤程式碼
}

與專案結合

序列化與反序列化

序列化(位元組化)

var buffer bytes.Buffer  // 容器
enc := gob.NewEncoder(buffer)  // 編碼器
err := enc.Encode(dest)  // 編碼

反序列化(反位元組化)

dec := gob.NewDecoder(bytes.NewReader(buffer.bytes()))  // 解碼器
dec.Decode(src)  // 解碼

李培冠部落格

歡迎訪問我的個人網站:

李培冠部落格:lpgit.com