处理流程
- 编写readfile.go
- 编写readfile.yml配置文件
- 编译成.so
- 启动kuiper
- 创建stream
- 查询所有
readfile.go
任务是读取txt文件,每读取一行就输出,读到最后结束。
其中,struct readfile为:
type readfile struct {
filepath string //文件路径
cancel context.CancelFunc
}
核心是实现方法Open()
func (s *readfile) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
t := time.NewTicker(1000 * time.Millisecond)
exeCtx, cancel := ctx.WithCancel()
s.cancel = cancel
go func(exeCtx api.StreamContext) {
defer t.Stop()
file, err := os.Open(s.filepath)
if err != nil{
print(err)
os.Exit(2)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
select {
case <-t.C:
str,err := reader.ReadBytes('\n')
if err == io.EOF {
println("read the file finished")
cancel()
os.Exit(2)
return
}
if err != nil {
println(err)
os.Exit(2)
}
str3 := string(str)
print(str3)
s.pattern["val"]=str3
api.NewDefaultSourceTuple(s.pattern,nil)
case <-exeCtx.Done():
return
}
}
}(exeCtx)
}
相关命令
//创建流
bin/cli create stream streamRead '(NUM STRING)WITH (DATASOURCE="topicRead", TYPE="readfile")'
//查询所有
bin/cli query
select * from streamRead
结果
通过执行完上面6步,预期结果是:
- 由于readfile.go中有一句
api.NewDefaultSourceTuple(msg_map,meta_map)
,应该会在query面板每隔1秒收到一条消息。 - 由于readfile.go中有一句
print(str3)
,应该在server面板每隔1秒打印读取到的字符串。
实际结果是:
第一条没有收到,第二条收到了
分析
读取文件成功,但是没有传出去,应该是Open()方法中,最后调用函数api.NewDefaultSourceTuple(msg_map,meta_map)
时,传入的参数有问题。
但是不传入map,编译为插件时不通过,会报错如下:
sources/readfile.go:59:30: cannot use msg_list (type []string) as type map[string]interface {} in argument to api.NewDefaultSourceTuple
sources/readfile.go:59:30: cannot use meta_list (type []string) as type map[string]interface {} in argument to api.NewDefaultSourceTuple
官方的对这个函数的说明:
https://github.com/emqx/kuiper/blob/master/docs/en_US/extension/source.md
Typically, use
api.NewDefaultSourceTuple(message, meta)
to create a SourceTuple. The meta data could be anything that worth to be recorded. For example, the qualified topic of the message. The first parameter is a StreamContext pointer. You can retrieve the context information and logger etc. from it.
.