我编写了独立调用多个http请求并合并结果的go代码。
有时组合方法会缺少值。
func profile(req *http.Request) (UserMe, error, UserRating, error) {
wgcall := &sync.WaitGroup{}
uChan := make(chan ResUser)
rChan := make(chan ResRating)
// variable inits
var meResp UserMe
var ratingResp UserRating
go func() {
res := <-uChan
meResp = res.Value
}()
go func() {
res := <-rChan
ratingResp = res.Value
}()
wgcall.Add(2)
go me(req, wgcall, uChan)
go rate(req, wgcall, rChan)
wgcall.Wait()
logrus.Info(meResp) // sometimes missing
logrus.Info(ratingResp) // sometimes missing
return meResp, meErr, ratingResp, ratingErr
}
但是 me 和 rating 调用会按预期返回来自 api 请求的值。
func me(req *http.Request, wg *sync.WaitGroup, ch chan ResUser) {
defer wg.Done()
// http call return value correclty
me := ...
ch <- ResUser{
Value := // value from rest
}
logrus.Info(fmt.Sprintf("User calls %v" , me)) // always return the values
close(ch)
}
func rate(req *http.Request, wg *sync.WaitGroup, ch chan ResRating) {
defer wg.Done()
// make http call
rating := ...
ch <- ResRating{
Value := // value from rest
}
logrus.Info(fmt.Sprintf("Ratings calls %v" , rating)) // always return the values
close(ch)
}
问题是:配置文件函数上的 meResp 和 ratingResp 并不总是获取值。有时只有 meResp 或 ratingResp,有时两者都符合预期。
但是我和 rate 函数调用总是获取值。
能帮我解决这个问题吗?
最佳答案
有一个 race condition在您的代码中。
没有任何障碍可以确保从 uChan
和 rChan
读取的 profile
方法中的 goroutines 已经填充了变量 meResp
和 ratingResp
在您从 profile
返回之前。
您可以通过在 profile
中放弃使用 channel 和内联声明的 goroutines 来极大地简化您的代码。相反,只需直接填充响应值。在这种情况下,使用 channel 或 goroutines 读取它们没有任何好处,因为您只打算发送一个值,并且您要求两个 HTTP 调用产生的值在返回之前存在。
您可以通过修改 me
和 rate
的签名来接收指向写入其输出的位置的指针,或者通过用一个小函数包装它们的调用来实现此目的它接收它们的输出值并填充 profile
中的值。重要的是,WaitGroup
应该只在 值被填充后发出信号:
wgcall := &sync.WaitGroup{}
var meResp UserMe
var ratingResp RatingMe
wgcall.Add(2)
// The "me" and "rate" functions should be refactored to
// drop the wait group and channel arguments.
go func() {
meResp = me(req)
wgcall.Done()
}()
go func() {
ratingResp = rate(req)
wgcall.Done()
}()
wgcall.Wait()
// You are guaranteed that if "me" and "rate" returned valid values,
// they are populated in "meResp" and "ratingResp" at this point.
// Do whatever you need here, such as logging or returning.
关于golang 发出并发请求并合并响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52498618/