是否有类似于Python/Java的异步数据存储API的Go语言版本?或者只能使用带有go
关键字的普通API呢?
是否有类似于Python/Java的异步数据存储API的Go语言版本?或者只能使用带有go
关键字的普通API呢?
对于任何AppEngine服务,Go没有与Python或Java异步API相对应的等效API。事实上,Go标准库也没有标准的异步风格。原因是在Go中,你使用阻塞式编写函数,并根据需要使用一些基本的并发原语来组合它们。虽然你不能仅仅在dastore.Get
调用之前添加go
,但这仍然是相对简单的。例如,考虑以下刻意构造的示例:
func loadUser(ctx appengine.Context, name strings) (*User, err) {
var u User
var entries []*Entry
done := make(chan error)
go func() {
// Load the main features of the User
key := datastore.NewKey(ctx, "user", name, 0, nil)
done <- datastore.Get(ctx, key)
}()
go func() {
// Load the entries associated with the user
q := datastore.NewQuery("entries").Filter("user", name)
keys, err := q.GetAll(ctx, &entries)
for i, k := range keys {
entries[i].key = k
}
done <- err
}()
success := true
// Wait for the queries to finish in parallel
for i := 0; i < 2 /* count the funcs above */; i++ {
if err := <-done; err != nil {
ctx.Errorf("loaduser: %s", err)
success = false
}
}
if !success {
return
}
// maybe more stuff here
}
Go语言中没有显式的异步API,需要使用go协程实现。我没有看到任何关于这方面的资料,但我猜测不提供异步API是因为使用go协程非常容易。