Contenu connexe
Similaire à らくちん Go言語 (20)
らくちん Go言語
- 6. 速いのは、まぁ当然。
• ネイティブコードですから。
• Web API 用途なら、ほぼ Nginx 並だと思ってOK。
• t2.micro で (lo) 8500 req/sec とか出てる。
• ちなみに Nginx が 9000 req/sec ぐらいかな。
• まぁパブリックIPだと 3000 req/sec 辺りで
ネットワーク的にカンストしちゃうんだけど。
- 8. PaaS の対応も充実
• Google App Engine はまぁ当然。
• Heroku 公式サポートもキタよー。
• Go support now official on Heroku
https://blog.heroku.com/archives/2015/7/7/go_support_now_official_on_heroku
(2015年7月7日)
• おなじみの git push heroku master でサクッと公開できたよ。
https://github.com/kamicup/solocounter
- 13. 例)ウェブAPI を作る
[ec2-user@ip-17x-xx-xx-xx ]$ yum -y install golang
[ec2-user@ip-17x-xx-xx-xx ]$ cat > main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello Gopher!")
})
http.ListenAndServe(":80", nil)
}
書いた―
- 14. 例)ウェブAPI を作る
[ec2-user@ip-17x-xx-xx-xx ]$ yum -y install golang
[ec2-user@ip-17x-xx-xx-xx ]$ cat > main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello Gopher!")
})
http.ListenAndServe(":80", nil)
}
[ec2-user@ip-17x-xx-xx-xx ]$ go run main.go
動いた!
- 15. 例)ウェブAPI を作る
[ec2-user@ip-17x-xx-xx-xx ]$ yum -y install golang
[ec2-user@ip-17x-xx-xx-xx ]$ cat > main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello Gopher!")
})
http.ListenAndServe(":80", nil)
}
[ec2-user@ip-17x-xx-xx-xx ]$ go run main.go
[ec2-user@ip-17x-xx-xx-xx ]$ go build main.go
ビルドしとくかー
- 24. channel
• 異なる goroutine 間で、任意の型付きデータを送
受信するための経路。
• 初期化時に決めた個数のバッファを持てる。
• 読み取りはブロックする。
• 書き込みはバッファが空いていればブロックしない。
- 28. go func() {
for {
value := <- queue
doSomething(value)
}
}()
チャネルを待ち受けて仕事する goroutine を動かしておきます。
(チャネルの読み取り「<-」は処理をブロックするので、
これで大丈夫です。CPUがブン回ったりはしません。)
- 30. go func() {
for {
value := <- queue
doSomething(value)
}
}()
さっきのこいつが、何かしらやってくれます。
- 31. $ go run main.go
[0] ほげほげ1
[1] ほげほげ2
[2] ほげほげ3
[0] ほげほげ4
[1] ほげほげ5
[2] ほげほげ6
[3] ほげほげ7
出力例(不定)
この例は 1対多 だけど 多対1 でも同じ要領です。
実験コード