Using Go with Redis

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

    • 在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)}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.