Reputation: 29
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?
Upvotes: 1
Views: 1152
Reputation: 3667
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.
Upvotes: 1