LoginSignup
2
1

More than 5 years have passed since last update.

Go+GAE+PubSubで躓いたはなし

Last updated at Posted at 2018-12-05

ローカルサーバーのインストール

たいして躓いたわけではないが、Endpointの設定を開発時はどうしてもローカルにしないと不便なので、必須。

//install
gcloud components install pubsub-emulator
// set env
$(gcloud beta emulators pubsub env-init)
//pubsub server start first
gcloud beta emulators pubsub start
//gae server with env
python  ~/google-cloud-sdk/platform/google_appengine/dev_appserver.py ./app.yaml --env_var PUBSUB_EMULATOR_HOST=${PUBSUB_EMULATOR_HOST}

localhost:8080をエンドポイントにするとバグるはなし(追記 2018/12/7)

https://stackoverflow.com/questions/38667386/testing-google-cloud-pubsub-push-endpoints-locally
2016年に話題になっている既知のバグのように見えますが、

eval $(gcloud beta emulators pubsub env-init)

これをbash_profileなどに入れておかないと起こります。要注意。

too many open files

大量のSubをローカルでテストしていると、OSのファイルオープン上限に達します。

2018/12/06 19:16:18 http: panic serving 127.0.0.1:63060: dialing: google: error getting credentials using well-known file (.config/gcloud/application_default_credentials.json): open .config/gcloud/application_default_credentials.json: too many open files

Macの人はこの記事を読んで設定しましょう。
https://qiita.com/sou_lab/items/1ca051a1f3b906a23dc8

ulimit -n 524288

もお忘れなく。

Workerでの受け取り方

https://github.com/GoogleCloudPlatform/golang-samples/blob/master/appengine_flexible/pubsub/pubsub.go
ここに書いてあるのだが、癖があるので要注意

sample.go(一部)
type OriginalMessage struct {
  V1 int
  V2 int
}
type pushRequest struct {
  Message struct {
    Attributes map[string]string
    Data       []byte
    ID         string `json:"message_id"`
  }
  Subscription string
}

func handler(w http.ResponseWriter, r *http.Request){
  var msg pushRequest 
  var orig OriginalMessage
  err := json.NewDecoder(r.Body).Decode(&msg);//r.Bodyには、pushRequestのような形で情報がきます
  err = json.Unmarshal(msg.Message.Data, &orig)//msg.Message.Dataをぬきとって、JSONにもどします。
}

func push(){
  var orig OriginalMessage{1,1}
  jsonBytes, err := json.Marshal(orig)
  msg := &pubsub.Message{Data: jsonBytes,}//渡したい構造体のJSONバイト配列をつっこみます
  pubr := topic.Publish(ctx, msg)//それでつくったMessageでPubします
}

半日躓きましたので、PubSubビギナー(俺もな)のみなさんは参考にしてください。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1