首頁 > 軟體

Go操作redis與redigo的範例解析

2022-04-14 10:01:04

Go-操作redis

安裝

golang操作redis的使用者端包有多個比如redigo、go-redis,github上Star最多的莫屬redigo。

github地址:https://github.com/garyburd/redigo 目前已經遷移到:https://github.com/gomodule/redigo

檔案:https://godoc.org/github.com/garyburd/redigo/redis

go get github.com/garyburd/redigo/redis
import "github.com/garyburd/redigo/redis"

連線

Conn介面是與Redis共同作業的主要介面,可以使用Dial,DialWithTimeout或者NewConn函數來建立連線,當任務完成時,應用程式必須呼叫Close函數來完成操作。

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
}

使用

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("SET", "name", "wd")
    if err != nil {
        fmt.Println("redis set error:", err)
    }
    name, err := redis.String(conn.Do("GET", "name"))
    if err != nil {
        fmt.Println("redis get error:", err)
    } else {
        fmt.Printf("Got name: %s n", name)
    }
}

設定key過期時間

  _, err = conn.Do("expire", "name", 10) //10秒過期
    if err != nil {
        fmt.Println("set expire error: ", err)
        return
    }

批次獲取mget、批次設定mset

_, err = conn.Do("MSET", "name", "wd","age",22)
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.Strings(conn.Do("MGET", "name","age"))
    if err != nil {
        fmt.Println("redis get error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s n", res_type)
        fmt.Printf("MGET name: %s n", res)
        fmt.Println(len(res))
    }
//結果:
//res type : []string 
//MGET name: [wd 22] 
//2

列表操作

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
    "reflect"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.String(conn.Do("LPOP", "list1"))
    if err != nil {
        fmt.Println("redis POP error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s n", res_type)
        fmt.Printf("res  : %s n", res)
    }
}
//res type : string 
//res  : ele3

hash操作

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
    "reflect"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("HSET", "student","name", "wd","age",22)
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.Int64(conn.Do("HGET", "student","age"))
    if err != nil {
        fmt.Println("redis HGET error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s n", res_type)
        fmt.Printf("res  : %d n", res)
    }
}
//res type : int64 
//res  : 22 

Pipelining(管道)

管道操作可以理解為並行操作,並通過Send(),Flush(),Receive()三個方法實現。使用者端可以使用send()方法一次性向伺服器傳送一個或多個命令,命令傳送完畢時,使用flush()方法將緩衝區的命令輸入一次性傳送到伺服器,使用者端再使用Receive()方法依次按照先進先出的順序讀取所有命令操作結果。

Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)
  • Send:傳送命令至緩衝區
  • Flush:清空緩衝區,將命令一次性傳送至伺服器
  • Recevie:依次讀取伺服器響應結果,當讀取的命令未響應時,該操作會阻塞。
package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    conn.Send("HSET", "student","name", "wd","age","22")
    conn.Send("HSET", "student","Score","100")
    conn.Send("HGET", "student","age")
    conn.Flush()
    res1, err := conn.Receive()
    fmt.Printf("Receive res1:%v n", res1)
    res2, err := conn.Receive()
    fmt.Printf("Receive res2:%vn",res2)
    res3, err := conn.Receive()
    fmt.Printf("Receive res3:%sn",res3)
}
//Receive res1:0 
//Receive res2:0
//Receive res3:22

redis釋出會訂閱模式

package main
import (
    "github.com/garyburd/redigo/redis"
    "fmt"
    "time"
)
func Subs() {  //訂閱者
    conn, err := redis.Dial("tcp", "10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :", err)
        return
    }
    defer conn.Close()
    psc := redis.PubSubConn{conn}
    psc.Subscribe("channel1") //訂閱channel1頻道
    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            fmt.Printf("%s: message: %sn", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Printf("%s: %s %dn", v.Channel, v.Kind, v.Count)
        case error:
            fmt.Println(v)
            return
        }
    }
}
func Push(message string)  { //釋出者
    conn, _ := redis.Dial("tcp", "10.1.210.69:6379")
    _,err1 := conn.Do("PUBLISH", "channel1", message)
       if err1 != nil {
             fmt.Println("pub err: ", err1)
                 return
            }

}
func main()  {
    go Subs()
    go Push("this is wd")
    time.Sleep(time.Second*3)
}
//channel1: subscribe 1
//channel1: message: this is wd

事務操作

MULTI, EXEC,DISCARD和WATCH是構成Redis事務的基礎,當然我們使用go語言對redis進行事務操作的時候本質也是使用這些命令。

MULTI:開啟事務

EXEC:執行事務

DISCARD:取消事務

WATCH:監視事務中的鍵變化,一旦有改變則取消事務。

範例:

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    conn.Send("MULTI")
    conn.Send("INCR", "foo")
    conn.Send("INCR", "bar")
    r, err := conn.Do("EXEC")
    fmt.Println(r)
}
//[1, 1]

萬能操作

連線redis

conn,err := redis.Dial(
  "tcp",
  "10.0.3.100:6379",
  redis.DialPassword("EfcHGSzKqg6cfzWq"),
  redis.DialDatabase(8))
if err != nil {
  fmt.Println("connect redis error :",err)
  return
}
defer conn.Close()

寫入

//寫入
//_, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
_, err = conn.Do("reids寫入方法", "key名字", "內容1","內容2","內容3")
if err != nil {
  fmt.Println("redis set error:", err)
}

讀取

//讀取
redis.Strings:返回多個
redis.String:返回一個
redis.int:返回統計的數位
//獲取集合所有成員
//name, err := redis.Strings(conn.Do("smembers", "beautiful_user"))
// 返回集合成員數
//name, err := redis.Int(conn.Do("scard", "beautiful_user"))
name, err := redis.方法名(conn.Do("redis讀取方法", "key名字"))
if err != nil {
  fmt.Println("redis get error:", err)
} else {
  fmt.Printf("Got name: %s n", name)
}

全部程式碼

package main
import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)
func main()  {
	conn,err := redis.Dial("tcp","10.0.3.100:6379",redis.DialPassword("EfcHGSzKqg6cfzWq"),redis.DialDatabase(8))
	if err != nil {
		fmt.Println("connect redis error :",err)
		return
	}
	defer conn.Close()
	//寫入
	_, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
	if err != nil {
		fmt.Println("redis set error:", err)
	}
	//讀取
	name, err := redis.Strings(conn.Do("smembers", "beautiful_user"))
	if err != nil {
		fmt.Println("redis get error:", err)
	} else {
		fmt.Printf("Got name: %s n", name)
	}
}

以上就是Go操作redis與redigo的範例解析的詳細內容,更多關於Go操作redis與redigo的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com