-
Notifications
You must be signed in to change notification settings - Fork 4
中文手册7(分组消息队列)
Li Donghai edited this page Jan 13, 2018
·
1 revision
import "github.com/jacoblai/yiyidb"
//取到当前程序所在物理位置
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
//参数1 数据库路径
//参数2 可能出现的key的最大长度
q, err := yiyidb.OpenChanQueue(dir + "/yiyiqueue", 10)
if err != nil {
fmt.Println(err)
return
}
defer queue.Close()
//对象定义
type object struct {
Value []byte
Key string
}
//实例化对象
msg := &object{}
msg.Key= "dkfjdkf"
msg.Value = []byte("ddddd")
//推送5条数据到名为“jac”的分组队列中
for i := 1; i <= 5; i++ {
msg.Key= "dkfjdkf" + strconv.Itoa(i)
msg.Value = []byte("ddddd"+ strconv.Itoa(i))
if item, err := q.EnqueueObject("jac", *msg); err == nil {
rmsg := &object{}
item.ToObject(rmsg)
fmt.Println("out",rmsg.Key, string(rmsg.Value))
}
}
//取得指定分组的所有队列中的数据
vals, _ := q.PeekStart("jac")
for _, v := range vals {
remsg := &object{}
err = v.ToObject(remsg)
if err != nil {
fmt.Println("send offline to object err:", err)
}
fmt.Println(remsg.Key, string(remsg.Value))
}
推入一些切片数据到“jac”分组队列中
for i := 1; i <= 5; i++ {
if _, err = q.Enqueue("jac", []byte(fmt.Sprintf("value for item %d", i))); err != nil {
t.Error(err)
}
}
推入一些切片数据到“quy”分组队列中
for i := 1; i <= 8; i++ {
if _, err = q.Enqueue("quy", []byte(fmt.Sprintf("value for item %d", i))); err != nil {
t.Error(err)
}
}
取出“jac”分组的数据(先进先出原则)
for i := 1; i <= 5; i++ {
deqItem, err := q.Dequeue("jac")
if err != nil {
t.Error(err)
}
fmt.Println("deq:", deqItem.ID, string(deqItem.Value))
}
取出“quy”分组的数据(先进先出原则)
for i := 1; i <= 8; i++ {
deqItem, err := q.Dequeue("quy")
if err != nil {
t.Error(err)
}
fmt.Println("deq:", deqItem.ID, string(deqItem.Value))
}
q.Clear("jac")
goos: darwin
goarch: amd64
200000 16136 ns/op 1259 B/op 21 allocs/op
PASS