你需要一个足够大小的缓冲区。对于简单的情况,缓冲的Go通道可以工作。
问问自己 - 在这个延迟期间需要存储多少数据 - 你应该有一个合理的上限。例如,如果您的流每秒最多传送N个数据包,那么要延迟7分钟,您需要存储420N数据包。
问问自己 - 如果在延迟窗口期间有多于预期的数据到达,会发生什么?您可以抛弃新数据,或抛弃旧数据,或者只是阻止输入流。哪些对您的方案可行?每种方案都会产生略有不同的解决方
问问自己 - 如何计算延迟?从创建流的那一刻起?从每个数据包到达的那一刻起?每个数据包的延迟是单独的,还是仅针对流中的第一个数据包?
为了开发一些示例代码,您需要在此处大大缩小设计选择范围。
对于这些设计选择的某些子集,这是在每个消息的通道之间添加延迟的简单方法:
package main import ( "fmt" "sync" "time" ) func main() { // in is a channel of strings with a buffer size of 10 in := make(chan string, 10) // out is an unbuffered channel out := make(chan string) // this goroutine forwards messages from in to out, ading a delay // to each message. const delay = 3 * time.Second go func() { for msg := range in { time.Sleep(delay) out <- msg } close(out) }() var wg sync.WaitGroup wg.Add(1) // this goroutine drains the out channel go func() { for msg := range out { fmt.Printf("Got '%s' at time %s\n", msg, time.Now().Format(time.Stamp)) } wg.Done() }() // Send some messages into the in channel fmt.Printf("Sending '%s' at time %s\n", "joe", time.Now().Format(time.Stamp)) in <- "joe" time.Sleep(2 * time.Second) fmt.Printf("Sending '%s' at time %s\n", "hello", time.Now().Format(time.Stamp)) in <- "hello" time.Sleep(4 * time.Second) fmt.Printf("Sending '%s' at time %s\n", "bye", time.Now().Format(time.Stamp)) in <- "bye" close(in) wg.Wait() }