Go-操作redis/redigo
目录
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:%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)
}
}
选择了IT,必定终身学习