Golang中如何检查通道在等待消息时是否在特定时间内为空

Golang中如何检查通道在等待消息时是否在特定时间内为空 我正在编写一个包含两个函数 readAndSendToCollectorcollectAndPushToStream 的 Go 代码。

func readAndSendToCollector(w http.ResponseWriter, req *http.Request) {
    b, _ := ioutil.ReadAll(req.Body)
    bytesReader := bytes.NewReader(b)
    bufReader := bufio.NewReader(bytesReader)
    value, _, _ := bufReader.ReadLine()
    if len(value) != 0 {
        if debug || fine {
            fmt.Printf("%s\n", time.Now().Format("2006-01-02 15:04:05")+" Reading the request payload")
        }
        mEntry := new(streaming.Entry)
        mEntry.Key = []byte("dkey")
        mEntry.Value = value
        chanMessage <- *mEntry
    } 

func collectAndPushToStream(chanMessage chan streaming.Entry) {
    wg.Add(1)
    defer wg.Done()
    var pmdEntry []streaming.PutMessagesDetailsEntry = make([]streaming.Entry, 0, 100)
    var MAX_PAYLOAD_SIZE = 1000000  //1mb
    var totalPayloadSize = 0
    var completeBytesTransferred = 0
    for mEntry := range chanMessage {
        //fmt.Printf("key = %s   Value = %s\n", mEntry.Key, mEntry.Value)
        entryPayloadSize := len(mEntry.Key) + len(mEntry.Value)
        if (totalPayloadSize + entryPayloadSize) > MAX_PAYLOAD_SIZE {
            pushMessagesToStream(pmdEntry)
            completeBytesTransferred = completeBytesTransferred + totalPayloadSize
            fmt.Println("totalPayloadSize = " + strconv.Itoa(totalPayloadSize))
            fmt.Println("totalMessages = " + strconv.Itoa(len(pmdEntry)))
            fmt.Println("completeBytesTransferred = " + strconv.Itoa(completeBytesTransferred))
            totalPayloadSize = 0 //reset the payload size
            pmdEntry = pmdEntry[:0]
        }
        pmdEntry = append(pmdEntry, mEntry)
        totalPayloadSize = totalPayloadSize + entryPayloadSize
    }
} 

这里的函数 readAndSendToCollector 从 HTTP 请求中读取有效载荷并将其推送到通道 chanMessage。 而 collectAndPushToStream 读取通道 chanMessage,收集 1MB 的数据并将其推送到流。

有时可能没有 1MB 的数据可用,我想等待 10 秒钟,如果通道中没有更多数据,我希望将可用的数据推送到流。 我该如何等待 10 秒并检查通道中是否有任何数据?


更多关于Golang中如何检查通道在等待消息时是否在特定时间内为空的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中如何检查通道在等待消息时是否在特定时间内为空的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用带有两个 case 的 select 语句,一个用于你的通道,另一个使用 time.After()

select {
case <-time.After(10*time.Second):
    return timeoutErr
case var1 := <-yourChannel:
    return handleVar(var1)
}
回到顶部