go - 如何处理 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
}
我们如何改进和测试这种情况下的最佳实践?
解决方案
将您的 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
更易于使用的并发映射。
推荐阅读
- node.js - 无法从 api 使用 redux 获取用户
- php - 如何减少mysql查询加载时间
- php - 非英语不支持来自 $.post jquery codeigniter 的 mysql 查询
- html - 在 td 标签中使用 `display:block` 从顶部开始文本?我需要将文本移到底部
- javascript - 当我转换它们时,会出现 div 左侧的一条线
- vba - 单击复选框时如何隐藏文本
- .htaccess - 使用 .htaccess 隐藏网址
- python - 在 pyqt5 中绘制 Matplotlib 图
- deap - 如何编写适用于数据框列的自定义函数作为 DEAP 的原语
- php - Laravel:在查询参数中再次获取 URL 参数