首先你需要安装redigo
go get github.com/garyburd/redigo/redis
使用go的(interface)接口实现,
话不多说,直接上代码。
package main
import (
"github.com/garyburd/redigo/redis"
)
var client redis.Conn
var err error
//接口定义
type RedisQueue interface {
create_queue() (string,string)
empty() (bool,string)
size() (int,string)
put(value string) string
get() (string,string)
}
//结构体
type Connect_args struct {
queue_name string
network string
address string
password string
}
//与redis建立连接 返回连接状态
func (connect_args Connect_args) create_queue() (string,string){
if(len(connect_args.password)==0){
client, err = redis.Dial(connect_args.network,connect_args.address,)
}else {
client, err = redis.Dial(connect_args.network,connect_args.address ,redis.DialPassword(connect_args.password))
}
if(err ==nil){
return "Connection success","ok"
}
return "Connection failed","error"
}
//队列是否为空 返回 true 或 false
func (connect_args Connect_args)empty() (bool,string){
replay,err :=client.Do("LLEN",connect_args.queue_name)
count, _ := replay.(int64)
if(err==nil){
if(count!=0){
return true,"ok"
}
return false,"ok"
}
return false,"error"
}
func (connect_args Connect_args)put(value string) string{
_,err :=client.Do("RPUSH",connect_args.queue_name,value)
if(err==nil){
return "ok"
}
return "error"
}
func (connect_args Connect_args)get() (string,string){
replay,err :=client.Do("LPOP",connect_args.queue_name)
value, _ := replay.(string)
if(err==nil){
return value,"ok"
}
return value,"error"
}
func (connect_args Connect_args)size() (int,string){
replay,err :=client.Do("LLEN",connect_args.queue_name)
count, _ := replay.(int64)
if(err==nil){
return int(count),"ok"
}
return 0,"error"
}
func main() {
var redis_queue RedisQueue = Connect_args{
"test",
"tcp",
"127.0.0.1:6379",
"123456"}
redis_queue.create_queue()
//是否为空
replay , err := redis_queue.empty()
println(replay,err)
//put进队列两个值
for a:=0 ; a < 2 ;a++{
err = redis_queue.put("s")
println(err)
}
//队列数量
s := -1
s ,err = redis_queue.size()
println(s,err)
//队列取值
for a:=0 ; a < s;a++{
redis_queue.get()
}
//队列数量
s ,err = redis_queue.size()
println(s,err)
}
结构体参数:
1 队列名字
2 连接redis时的连接方式,一般都是tcp
3 连接地址,(“127.0.0.1:6379” ) host:port 的形式
4 密码 ,如果不需要密码,结构体赋值时(“123456”)更改为(“”)
每个函数的返回值都是两个(返回的值+是否错误的状态)(除了put函数时一个返回值)
ok为连接正确没有错误。error为连接失败错误。
欢迎进(Q)群,帮你解决问题: