首页 > 解决方案 > 如何处理 GRPC Golang 高 CPU 使用率

问题描述

我们在使用 grpc 流式传输交易的 golang 函数中存在可疑的高 CPU 使用率。功能很简单,当我们从前端收到 ORDER ID 数据变化的请求,然后我们消费并流回来。

这里的代码

func (consumer OrderChangesConsumer) Serve(message string) {
    response := messages.OrderChanges{}
    if err := json.Unmarshal([]byte(message), &response); err != nil {
        logData := map[string]interface{}{
            "message": message,
        }
        seelog.Error(commonServices.GenerateLog("parse_message_error", err.Error(), &logData))
    }

    if response.OrderID > 0 {
        services.PublishChanges(response.OrderID, &response)
    }
}




// PublishChanges sends the order change message to the changes channel.
func PublishChanges(orderID int, orderChanges *messages.OrderChanges) {
    orderMutex.RLock()
    defer orderMutex.RUnlock()
    orderChan, ok := orderChans[orderID]
    if !ok {
        return
    }
    orderChan <- orderChanges
}

pprof

我们如何改进和测试这种情况下的最佳实践?

标签: gogrpccpucpu-usage

解决方案


将您的 PublishChanges 代码更新为以下内容,看看是否有帮助:

// PublishChanges sends the order change message to the changes channel.
func PublishChanges(orderID int, orderChanges *messages.OrderChanges) {
    orderMutex.RLock()
    orderChan, ok := orderChans[orderID]
    orderMutex.RUnlock()
    if !ok {        
        return
    }
    orderChan <- orderChanges
}

您可能还想考虑使用sync.Map更易于使用的并发映射。


推荐阅读