当前位置: > > > > 持续接收 JSON 并根据时间段写入磁盘的最佳方式
持续接收 JSON 并根据时间段写入磁盘的最佳方式
来源:stackoverflow
2024-04-26 16:33:29
0浏览
收藏
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《持续接收 JSON 并根据时间段写入磁盘的最佳方式》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容
我很难想出一个解决方案来不断接收 json 并将其附加到切片,然后根据内部设定的时间定期将其写入磁盘。我想出了一个解决方案,但是在没有任何同步的情况下读取/写入同一片。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"runtime"
"strconv"
"time"
)
type Message map[string]interface{}
type Messages []Message
var (
messages Messages
)
func main() {
c := make(chan Message)
var messages Messages
go func() {
tick := time.Tick(200 * time.Millisecond)
for {
select {
case <-tick:
mb := []byte(`{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }`)
var message Message
json.Unmarshal(mb, &message)
c <- message
}
}
}()
go func() {
tick := time.Tick(30 * time.Second)
for {
select {
case <-tick:
content, _ := json.Marshal(messages)
now := time.Now().Unix()
filename := "test" + strconv.FormatInt(now, 10) + ".json"
err := ioutil.WriteFile(filename, content, 0644)
if err != nil {
panic(err)
}
messages = nil
}
}
}()
for {
newmessage := <-c
messages = append(messages, newmessage)
}
}
预计每 30 秒 1 个文件,其中包含过去 30 秒内收到的所有消息,且没有丢失的消息。
解决方案
您的解决方案看起来不错,除了同步部分:
var (
messages messages
lock sync.mutex
)
...
newmessage := <-c
lock.lock()
messages = append(messages, newmessage)
lock.unlock()
供阅读:
case <-tick:
// Take a snapshot of messages, and reset it
lock.Lock()
msgs:=messages
messages=Messages{}
lock.Unlock()
content, _ := json.Marshal(msgs)
// No need for messages=nil
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持米云!更多关于Golang的相关知识,也可关注米云公众号。
