github.com/TeaOSLab/EdgeNode@v1.3.8/internal/monitor/value_queue.go (about) 1 // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. 2 3 package monitor 4 5 import ( 6 "encoding/json" 7 "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" 8 teaconst "github.com/TeaOSLab/EdgeNode/internal/const" 9 "github.com/TeaOSLab/EdgeNode/internal/events" 10 "github.com/TeaOSLab/EdgeNode/internal/goman" 11 "github.com/TeaOSLab/EdgeNode/internal/remotelogs" 12 "github.com/TeaOSLab/EdgeNode/internal/rpc" 13 "github.com/iwind/TeaGo/maps" 14 "time" 15 ) 16 17 var SharedValueQueue = NewValueQueue() 18 19 func init() { 20 if !teaconst.IsMain { 21 return 22 } 23 24 events.On(events.EventLoaded, func() { 25 goman.New(func() { 26 SharedValueQueue.Start() 27 }) 28 }) 29 } 30 31 // ValueQueue 数据记录队列 32 type ValueQueue struct { 33 valuesChan chan *ItemValue 34 } 35 36 func NewValueQueue() *ValueQueue { 37 return &ValueQueue{ 38 valuesChan: make(chan *ItemValue, 1024), 39 } 40 } 41 42 // Start 启动队列 43 func (this *ValueQueue) Start() { 44 // 这里单次循环就行,因为Loop里已经使用了Range通道 45 err := this.Loop() 46 if err != nil { 47 remotelogs.ErrorObject("MONITOR_QUEUE", err) 48 } 49 } 50 51 // Add 添加数据 52 func (this *ValueQueue) Add(item string, value maps.Map) { 53 valueJSON, err := json.Marshal(value) 54 if err != nil { 55 remotelogs.Error("MONITOR_QUEUE", "marshal value error: "+err.Error()) 56 return 57 } 58 select { 59 case this.valuesChan <- &ItemValue{ 60 Item: item, 61 ValueJSON: valueJSON, 62 CreatedAt: time.Now().Unix(), 63 }: 64 default: 65 66 } 67 } 68 69 // Loop 单次循环 70 func (this *ValueQueue) Loop() error { 71 rpcClient, err := rpc.SharedRPC() 72 if err != nil { 73 return err 74 } 75 76 for value := range this.valuesChan { 77 _, err = rpcClient.NodeValueRPC.CreateNodeValue(rpcClient.Context(), &pb.CreateNodeValueRequest{ 78 Item: value.Item, 79 ValueJSON: value.ValueJSON, 80 CreatedAt: value.CreatedAt, 81 }) 82 if err != nil { 83 if rpc.IsConnError(err) { 84 remotelogs.Warn("MONITOR", err.Error()) 85 } else { 86 remotelogs.Error("MONITOR", err.Error()) 87 } 88 continue 89 } 90 } 91 return nil 92 }