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 …]

转载于:https://www.cnblogs.com/wanghaijun999/p/8408589.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐