6

是否有与 Python/Java 的异步数据存储 API 类似的 Go?或者可以只使用带有go关键字的普通 API 吗?

4

2 回答 2

13

对于任何 AppEngine 服务,没有与 Python 或 Java 异步 API 等效的 Go。事实上,Go 标准库也没有任何标准异步风格。原因是在 Go 中,您使用阻塞样式编写函数,并根据需要使用一些基本的并发原语来组合它们。虽然您不能只godastore.Get通话开始时添加,但它仍然相对简单。考虑以下人为的示例:

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
}

这种相同的方法几乎可以用于任何需要同时运行多个可能需要一段时间的事情的上下文,无论是数据存储调用、urlfetch、文件加载等。

于 2013-03-02T02:13:50.620 回答
2

Go 中没有明确的异步 API。您应该改用 go 例程。我还没有看到任何有关这方面的资料,但我怀疑异步 API 不存在,因为使用 go 例程非常容易。

于 2013-03-01T22:46:40.590 回答