英文:
How to handle GRPC Golang High CPU Usage
问题
我们的golang函数在使用grpc流式传输事务时,出现了可疑的高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将订单更改消息发送到更改通道。
func PublishChanges(orderID int, orderChanges *messages.OrderChanges) {
orderMutex.RLock()
defer orderMutex.RUnlock()
orderChan, ok := orderChans[orderID]
if !ok {
return
}
orderChan <- orderChanges
}
我们如何改进和测试这种情况的最佳实践?
英文:
We have suspicious high cpu usage in our golang function that we using grpc to stream our transaction. The function is simple, when we got request of ORDER ID data changes from frontend, then we consume and stream back.
Here the code
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
}
How we can improve and test the best practice for this case?
答案1
得分: 1
请更新您的PublishChanges
代码如下,并查看是否有所帮助:
// PublishChanges 将订单更改消息发送到更改通道。
func PublishChanges(orderID int, orderChanges *messages.OrderChanges) {
orderMutex.RLock()
orderChan, ok := orderChans[orderID]
orderMutex.RUnlock()
if !ok {
return
}
orderChan <- orderChanges
}
您可能还希望考虑使用sync.Map
来更轻松地使用并发映射。
英文:
Would update your PublishChanges code to the following and see if that helps:
// 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
}
You might also want to consider using sync.Map
for an easier to use concurrent map.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论