首頁  >  文章  >  資料庫  >  Go操作redis與redigo的方法

Go操作redis與redigo的方法

WBOY
WBOY轉載
2023-05-30 21:25:101016瀏覽

Go-操作redis

安裝

golang作業redis的客戶端套件有多個例如redigo、go-redis,github上Star最多的莫屬redigo。

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:%v\n",res2)
    res3, err := conn.Receive()
    fmt.Printf("Receive res3:%s\n",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: %s\n", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Printf("%s: %s %d\n", 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的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除