這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
-
- 在Go語言中使用redis資料庫
- 串連到Redis
- 儲存和擷取資料
- 解碼成json
- 最後應該在web應用中使用一個串連池
在Go語言中使用redis資料庫
日期:2016-09-13
作者:未知
原文:https://dinosaurscode.xyz/go/2016/09/13/using-go-with-redis/?utm_source=studygolang&utm_medium=email&nsukey=d7foHOu2JWuVtNx567nmYebGiV3xA77Y66gJwySUW6tBi9LTombwJLWAzrYVdYP1IZH1MZzOhcz%2BGh8xt%2FggTToFElonX%2FrUuMc%2B%2FT0eQnzrZLJM7%2BkF8QNBQ3zfhlNkQ5ZlFiDb04jx4X98ZPqSHPtXwX%2FOUW8sfR18L2zkUq0SZFfhtAfvWDtYlCg1unfC
翻譯: 一花一世界
時間:2016-10-23
排版:馬克飛象(https://maxiang.io)
本文
在這個範例中,你將看到怎樣在GO中使用Redis。 首先同時最重要的是串連redis服務,用如下的命令
$ go get github.com/garyburd/redigo
接著,確認你已經安裝了redis和啟動了redis伺服器
$ redis-server
串連到Redis
函數redis.Dial()返回一個redis.Conn的類型,用於發送命令到redis伺服器,並返回一個應答。
package mainimport "fmt"import "github.com/garyburd/redigo/redis"func main() { // Connect to the default port conn, err := redis.Dial("tcp", ":6379") if err != nil { panic(err.Error()) } defer conn.Close() // Send Redis a ping command and wait for a pong pong, _ := conn.Do("PING") fmt.Println(pong) // Output: PONG}
儲存和擷取資料
設定一個字串
ok, _ := conn.Do("SET", "name", "john")fmt.Println(ok)// Output: OK
取值
name, _ := conn.Do("GET", "name")fmt.Println(name)// Output: [106 111 104 110]
噢, 不,那不是我想要的結果。
有時,你想明確的把結果轉成和適當的類型, 這可以用類型斷言或是redigo的協助函數。
// 注意用外層用redis.Stirng()封裝name, _ := redis.String(conn.Do("GET", "name"))fmt.Println(name)// Output: john
解碼成json
你可以把一個複雜的資料類型,例如結構體用json的格式存起來。
// 把結構體存在json結構中, 用列表的形式存取。type User struct { Name string Age int}user1 := User{"John", 22}encoded, _ := json.Marshal(user1)conn.Do("LPUSH", "users", encoded)
現在解碼到一個結構體中
//從redis中提取,並解碼到一個結構中type User struct { Name string Age int}var unencoded *User // 把使用者列表映射到一個名為users的字串數組中users, _ := redis.Strings(conn.Do("LRANGE", "users", 0, -1))// 抽取一個字元,然後把它轉成位元組類型,然後解碼到unencodedjson.Unmarshal([]byte(users[0]), &unencoded)fmt.Println(unencoded.Name)// 輸出: John
最後,應該在web應用中使用一個串連池
http開發人員應該從串連池中擷取一個串連,並且當完成時,關閉它。
package mainimport "github.com/garyburd/redigo/redis"import "net/http"// Global pool that handlers can grab a connection fromvar pool = newPool()// Pool configurationfunc newPool() *redis.Pool { return &redis.Pool{ MaxIdle: 80, MaxActive: 12000, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") }, }}func home(res http.ResponseWriter, req *http.Request) { // Grab a connection and make sure to close it with defer conn := pool.Get() defer conn.Close() pong, _ := redis.Bytes(conn.Do("PING")) res.Write(pong)}func main() { http.HandleFunc("/", home) http.ListenAndServe(":8080", nil)}