GAE Go - 异步数据存储API?

Mat*_*w H 6 google-app-engine asynchronous go

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

Kyl*_*ons 13

对于任何AppEngine服务,没有Go等效于Python或Java异步API.实际上,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
}
Run Code Online (Sandbox Code Playgroud)

无论是数据存储调用,urlfetch,文件加载等,都可以在几乎任何需要同时运行多个事物的上下文中使用相同的方法.

  • Go运行时将许多goroutine复用到单个操作系统线程上.实际上,甚至在AppEngine之外的默认值是GOMAXPROCS = 1,这意味着只有一个goroutine将主动运行您的代码.但是,尽管如此,运行时在goroutine之间来回交换,阻塞,执行系统调用或等待锁定. (2认同)
  • 究竟.运行时来回交换,以便在有任何内容可以运行时始终运行. (2认同)