You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package timer
import (
"fmt"
"math/rand"
"time"
"github.com/toolkits/pkg/logger"
"github.com/didi/nightingale/v5/models"
)
// UpdateAlias 对于上报的监控数据会缓存在内存里然后周期性更新其alias
// 主要是性能考虑要不然每秒上报千万条监控指标每条都去更新alias耗时太久
// server是无状态的对于某个ident如果刚开始上报alias1到server1后来上报alias2到server2
// 如果server1和server2同时去更新数据库可能会造成混乱一会是alias1一会是alias2
// 所以models.UpdateAlias中做了一个逻辑先清空了15s之前的数据这样就可以保证只需要更新新数据即可
// go进程中的AliasMapper这个变量在进程运行时间久了之后不知道是否会让内存持续增长而不释放
// 如果真的出现这个问题可能要考虑把这个变量的存储放到redis之类的KV中
func UpdateAlias() {
go loopUpdateAlias()
}
func loopUpdateAlias() {
randtime := rand.Intn(2000)
fmt.Printf("timer: update alias: random sleep %dms\n", randtime)
time.Sleep(time.Duration(randtime) * time.Millisecond)
// 5s跑一次只会使用最近15s有过更新的数据在models.UpdateAlias有15s的清理逻辑
interval := time.Duration(5) * time.Second
for {
time.Sleep(interval)
updateAlias()
}
}
func updateAlias() {
err := models.UpdateAlias()
if err != nil {
logger.Warningf("UpdateAlias fail: %v", err)
}
}