go 文件驱动的队列
项目地址 https://github.com/nsqio/go-diskqueue
示例代码
package main
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"path"
"strconv"
"sync"
"time"
)
var dqip Interface
func NewTestLogger1() AppLogFunc {
return func(lvl LogLevel, f string, args ...interface{}) {
fmt.Sprintf(lvl.String()+": "+f, args...)
}
}
func InitQueue() {
l := NewTestLogger1()
tmpDirIp, _ := ioutil.TempDir("/c", "")
dqip = New("disk_queue_ip", tmpDirIp, 1024, 4, 1<<10, 2500, 2*time.Second, l)
}
func main() {
InitQueue()
go WriteToQueueIp()
ReadFromQueueIp()
}
func WriteToQueueIp() {
i := 10000
for {
i++
println("putting ip")
dqip.Put([]byte(strconv.Itoa(i)))
time.Sleep(1 * time.Second)
}
}
func ReadFromQueueIp() []byte {
for {
println("read ip")
ip := <-dqip.ReadChan()
ipstr := string(ip)
println(ipstr)
time.Sleep(1 * time.Second)
}
}
注意事项:
项目里的测试代码使用了临时随机目录,我们在项目里面使用的时候一定要使用固定目录,不然的话就失去了文件驱动队列的意义,项目重启后就无法继续以前的队列,导致数据丢失。
原理:
数据文件 :编号递增
位置文件记录消费的位置