chan实现控制速率
2018-09-21 本文已影响0人
斯嘎啦
MailWorkerChan := make(chan int, workerConfig.Mail)
func SendMailList(L []*model.Mail) {
for _, mail := range L {
MailWorkerChan <- 1
go SendMail(mail)
}
}
func SendMail(mail *model.Mail) {
defer func() {
<-MailWorkerChan
}()
url := g.Config().Api.Mail
r := httplib.Post(url).SetTimeout(5*time.Second, 30*time.Second)
r.Param("tos", mail.Tos)
r.Param("subject", mail.Subject)
r.Param("content", mail.Content)
resp, err := r.String()
if err != nil {
log.Errorf("send mail fail, receiver:%s, subject:%s, cotent:%s, error:%v", mail.Tos, mail.Subject, mail.Content, err)
}
log.Debugf("send mail:%v, resp:%v, url:%s", mail, resp, url)
}
该代码节选自open-falcon
的alarm
模块中发送邮件的部分,主要通过MailWorkerChan
实现控制速率。