You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 1.3 kB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. ## Cloud Pub/Sub [![GoDoc](https://godoc.org/cloud.google.com/go/pubsub?status.svg)](https://godoc.org/cloud.google.com/go/pubsub)
  2. - [About Cloud Pubsub](https://cloud.google.com/pubsub/)
  3. - [API documentation](https://cloud.google.com/pubsub/docs)
  4. - [Go client documentation](https://godoc.org/cloud.google.com/go/pubsub)
  5. - [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/pubsub)
  6. ### Example Usage
  7. First create a `pubsub.Client` to use throughout your application:
  8. [snip]:# (pubsub-1)
  9. ```go
  10. client, err := pubsub.NewClient(ctx, "project-id")
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. ```
  15. Then use the client to publish and subscribe:
  16. [snip]:# (pubsub-2)
  17. ```go
  18. // Publish "hello world" on topic1.
  19. topic := client.Topic("topic1")
  20. res := topic.Publish(ctx, &pubsub.Message{
  21. Data: []byte("hello world"),
  22. })
  23. // The publish happens asynchronously.
  24. // Later, you can get the result from res:
  25. ...
  26. msgID, err := res.Get(ctx)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. // Use a callback to receive messages via subscription1.
  31. sub := client.Subscription("subscription1")
  32. err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
  33. fmt.Println(m.Data)
  34. m.Ack() // Acknowledge that we've consumed the message.
  35. })
  36. if err != nil {
  37. log.Println(err)
  38. }
  39. ```