1. 程式人生 > >golang基於redis搭建佇列

golang基於redis搭建佇列

首先你需要安裝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為連線失敗錯誤。