1.安装一个redis server
提供一个下载地址:https://github.com/MicrosoftArchive/redis/releases
2.找到安装redis的路径,执行如下命令启动server
redis-server.exe redis.windows.conf
3.启动一个客户端
redis-cli.exe
go 连接redis需要使用第三方库redigo
1)安装redigo
go get github.com/garyburd/redigo/redis
连接读写:set
package main
import(
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c ,err:= redis.Dial("tcp","127.0.0.1:6379") //连接
if err !=nil {
fmt.Println("failed to connection redis server",err)
return
}
defer c.Close()
_,err =c.Do("set","surname","wang") //写入数据
if err != nil {
fmt.Println("write failed:",err)
return
}
r,err :=redis.String( c.Do("get","surname")) //读取数据
if err != nil {
fmt.Println("read failed:",err)
return
}
fmt.Printf(r)
}
存储hash表:
package main
import(
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c ,err:= redis.Dial("tcp","127.0.0.1:6379") //连接
if err !=nil {
fmt.Println("failed to connection redis server",err)
return
}
defer c.Close()
_,err =c.Do("HSet","student","name","wang") //写入数据
if err != nil {
fmt.Println("write failed:",err)
return
}
r,err :=redis.String( c.Do("HGet","student","name")) //读取数据
if err != nil {
fmt.Println("read failed:",err)
return
}
fmt.Printf(r)
}
队列操作:
package main
import(
"fmt"
"github.com/garyburd/redigo/redis"
)
func main() {
c ,err:= redis.Dial("tcp","127.0.0.1:6379") //连接
if err !=nil {
fmt.Println("failed to connection redis server",err)
return
}
defer c.Close()
_,err =c.Do("lpush","child","wangsan","lisi","zhaowu") //写入数据到队列
if err != nil {
fmt.Println("write failed:",err)
return
}
r,err :=redis.String( c.Do("lpop","child")) //读取数据
if err != nil {
fmt.Println("read failed:",err)
return
}
fmt.Printf(r)
}
一些批量操作:
批量写入读取
MGET key [key …]
MSET key value [key value …]
批量写入读取对象(Hashtable)
HMSET key field value [field value …]
HMGET key field [field …]
所有评论(0)