Debian Codegraph @

internal/website/content/howto/pubsub/subscribe.md

raw
1 ---
2 title: "Subscribe to Messages from a Topic"
3 date: 2019-03-26T09:44:33-07:00
4 lastmod: 2019-07-29T12:00:00-07:00
5 weight: 2
6 toc: true
7 ---
8
9 Subscribing to receive message from a topic with the Go CDK takes three steps:
10
11 1. [Open a subscription][] to a topic with the Pub/Sub service of your choice (once per
12 subscription).
13 2. [Receive and acknowledge messages][] from the topic. After completing any
14 work related to the message, use the Ack method to prevent it from being
15 redelivered.
16
17 [Open a subscription]: {{< ref "#opening" >}}
18 [Receive and acknowledge messages]: {{< ref "#receiving" >}}
19
20 <!--more-->
21
22 ## Opening a Subscription {#opening}
23
24 The first step in subscribing to receive messages from a topic is
25 to instantiate a portable [`*pubsub.Subscription`][] for your service.
26
27 The easiest way to do so is to use [`pubsub.OpenSubscription`][]
28 and a service-specific URL pointing to the topic, making sure you
29 ["blank import"][] the driver package to link it in.
30
31 ```go
32 import (
33 "context"
34
35 "gocloud.dev/pubsub"
36 _ "gocloud.dev/pubsub/<driver>"
37 )
38 ...
39 ctx := context.Background()
40 subs, err := pubsub.OpenSubscription(ctx, "<driver-url>")
41 if err != nil {
42 return fmt.Errorf("could not open topic subscription: %v", err)
43 }
44 defer subs.Shutdown(ctx)
45 // subs is a *pubsub.Subscription; see usage below
46 ...
47 ```
48
49 See [Concepts: URLs][] for general background and the [guide below][]
50 for URL usage for each supported service.
51
52 Alternatively, if you need fine-grained
53 control over the connection settings, you can call the constructor function in
54 the driver package directly (like `gcppubsubv2.OpenSubscription`).
55
56 ```go
57 import "gocloud.dev/pubsub/<driver>"
58 ...
59 subs, err := <driver>.OpenSubscription(...)
60 ...
61 ```
62
63 You may find the [`wire` package][] useful for managing your initialization code
64 when switching between different backing services.
65
66 See the [guide below][] for constructor usage for each supported service.
67
68 [guide below]: {{< ref "#services" >}}
69 [`pubsub.OpenSubscription`]:
70 https://godoc.org/gocloud.dev/pubsub#OpenTopic
71 ["blank import"]: https://golang.org/doc/effective_go.html#blank_import
72 [Concepts: URLs]: {{< ref "/concepts/urls.md" >}}
73 [`wire` package]: http://github.com/google/wire
74
75 ## Receiving and Acknowledging Messages {#receiving}
76
77 A simple subscriber that operates on
78 [messages](https://godoc.org/gocloud.dev/pubsub#Message) serially looks like
79 this:
80
81 {{< goexample src="gocloud.dev/pubsub.ExampleSubscription_Receive" imports="0" >}}
82
83 If you want your subscriber to operate on incoming messages concurrently,
84 you can start multiple goroutines:
85
86 {{< goexample src="gocloud.dev/pubsub.ExampleSubscription_Receive_concurrent" imports="0" >}}
87
88 Note that the [semantics of message delivery][] can vary by backing service.
89
90 [`*pubsub.Subscription`]: https://godoc.org/gocloud.dev/pubsub#Subscription
91 [semantics of message delivery]: https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
92
93 ## Other Usage Samples
94
95 * [CLI Sample](https://github.com/google/go-cloud/tree/master/samples/gocdk-pubsub)
96 * [Order Processor sample](https://gocloud.dev/tutorials/order/)
97 * [pubsub package examples](https://godoc.org/gocloud.dev/pubsub#pkg-examples)
98
99 ## Supported Pub/Sub Services {#services}
100
101 ### Google Cloud Pub/Sub {#gcp}
102
103 The Go CDK can receive messages from a Google [Cloud Pub/Sub][] subscription.
104 The URLs use the project ID and the subscription ID.
105
106 [Cloud Pub/Sub]: https://cloud.google.com/pubsub/docs/
107
108 `pubsub.OpenSubscription` will use Application Default Credentials; if you have
109 authenticated via [`gcloud auth application-default login`][], it will use those credentials. See
110 [Application Default Credentials][GCP creds] to learn about authentication
111 alternatives, including using environment variables.
112
113 [GCP creds]: https://cloud.google.com/docs/authentication/production
114 [`gcloud auth application-default login`]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
115
116 {{< goexample "gocloud.dev/pubsub/gcppubsubv2.Example_openSubscriptionFromURL" >}}
117
118 #### Google Cloud Pub/Sub Constructor {#gcp-ctor}
119
120 The [`gcppubsubv2.OpenSubscription`][] constructor opens a Cloud Pub/Sub
121 subscription. You must first obtain [GCP credentials][GCP creds] and then
122 create a gRPC connection to Cloud Pub/Sub. (This gRPC connection can be
123 reused among subscriptions.)
124
125 {{< goexample "gocloud.dev/pubsub/gcppubsubv2.ExampleOpenSubscription" >}}
126
127 [`gcppubsubv2.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/gcppubsubv2#OpenSubscription
128
129 ### Amazon Simple Queueing Service {#sqs}
130
131 The Go CDK can subscribe to an Amazon [Simple Queueing Service][SQS] (SQS)
132 topic. SQS URLs closely resemble the the queue URL, except the leading
133 `https://` is replaced with `awssqs://`. You should specify the `region`
134 query parameter to ensure your application connects to the correct region.
135
136 [SQS]: https://aws.amazon.com/sqs/
137
138 `pubsub.OpenSubscription` will open a subscription using a default AWS Config.
139
140 {{< goexample "gocloud.dev/pubsub/awssnssqs.Example_openSubscriptionFromURL" >}}
141
142 If your messages are being sent to SQS directly, or if they are being delivered
143 via an SNS topic with `RawMessageDelivery` enabled, set a `raw=true` query
144 parameter in your URL, or set `SubscriberOptions.Raw` to `true` if you're using
145 the constructors. By default, the subscription will use heuristics to identify
146 whether the message bodies are raw or [SNS JSON][].
147
148 Messages with a `base64encoded` message attribute will be automatically
149 [Base64][] decoded before being returned. See the [SNS publishing guide][]
150 or the [SQS publishing guide][] for more details.
151
152 [Base64]: https://en.wikipedia.org/wiki/Base64
153 [SNS publishing guide]: {{< ref "./publish.md#sns" >}}
154 [SQS publishing guide]: {{< ref "./publish.md#sqs" >}}
155 [SNS JSON]: https://aws.amazon.com/sns/faqs/#Raw_message_delivery
156
157 #### Amazon SQS Constructor {#sqs-ctor}
158
159 The [`awssnssqs.OpenSubscription`][] constructor opens an SQS queue. You must
160 first create an AWS Config with the same region as your topic:
161
162 {{< goexample "gocloud.dev/pubsub/awssnssqs.ExampleOpenSubscription" >}}
163
164 [`awssnssqs.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/awssnssqs#OpenSubscription
165
166 ### Azure Service Bus {#azure}
167
168 The Go CDK can recieve messages from an [Azure Service Bus][] subscription.
169 The URL for subscribing is the topic name with the
170 subscription name in the `subscription` query parameter.
171 `pubsub.OpenSubscription` will use the environment variable
172 `SERVICEBUS_CONNECTION_STRING` to obtain the Service Bus Connection String
173 you need to copy [from the Azure portal][Azure connection string].
174
175 {{< goexample "gocloud.dev/pubsub/azuresb.Example_openSubscriptionFromURL" >}}
176
177 [AMQP 1.0]: https://www.amqp.org/
178 [Azure connection string]: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions#get-the-connection-string
179 [Azure Service Bus]: https://azure.microsoft.com/en-us/services/service-bus/
180
181 #### Azure Service Bus Constructor {#azure-ctor}
182
183 The [`azuresb.OpenSubscription`][] constructor opens an Azure Service Bus
184 subscription. You must first connect to the topic and subscription using the
185 [Azure Service Bus library][] and then pass the subscription to
186 `azuresb.OpenSubscription`. There are also helper functions in the `azuresb`
187 package to make this easier.
188
189 {{< goexample "gocloud.dev/pubsub/azuresb.ExampleOpenSubscription" >}}
190
191 [`azuresb.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/azuresb#OpenSubscription
192 [Azure Service Bus library]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus
193
194 ### RabbitMQ {#rabbitmq}
195
196 The Go CDK can receive messages from an [AMQP 0.9.1][] queue, the dialect of
197 AMQP spoken by [RabbitMQ][]. A RabbitMQ URL only includes the queue name.
198 The RabbitMQ's server is discovered from the `RABBIT_SERVER_URL` environment
199 variable (which is something like `amqp://guest:guest@localhost:5672/`).
200
201 {{< goexample "gocloud.dev/pubsub/rabbitpubsub.Example_openSubscriptionFromURL" >}}
202
203 [AMQP 0.9.1]: https://www.rabbitmq.com/protocol.html
204 [RabbitMQ]: https://www.rabbitmq.com
205
206 #### RabbitMQ Constructor {#rabbitmq-ctor}
207
208 The [`rabbitpubsub.OpenSubscription`][] constructor opens a RabbitMQ queue.
209 You must first create an [`*amqp.Connection`][] to your RabbitMQ instance.
210
211 {{< goexample "gocloud.dev/pubsub/rabbitpubsub.ExampleOpenSubscription" >}}
212
213 [`*amqp.Connection`]: https://pkg.go.dev/github.com/rabbitmq/amqp091-go#Connection
214 [`rabbitpubsub.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/rabbitpubsub#OpenSubscription
215
216 ### NATS {#nats}
217
218 The Go CDK can publish to a [NATS][] subject. A NATS URL only includes the
219 subject name. The NATS server is discovered from the `NATS_SERVER_URL`
220 environment variable (which is something like `nats://nats.example.com`).
221
222 {{< goexample "gocloud.dev/pubsub/natspubsub.Example_openSubscriptionFromURL" >}}
223
224 NATS guarantees at-most-once delivery; it will never redeliver a message.
225 Therefore, `Message.Ack` is a no-op.
226
227 To parse messages [published via the Go CDK][publish#nats], the NATS driver
228 will first attempt to decode the payload using [gob][]. Failing that, it will
229 return the message payload as the `Data` with no metadata to accomodate
230 subscribing to messages coming from a source not using the Go CDK.
231
232 [gob]: https://golang.org/pkg/encoding/gob/
233 [NATS]: https://nats.io/
234 [publish#nats]: {{< ref "./publish.md#nats" >}}
235
236 #### NATS Constructor {#nats-ctor}
237
238 The [`natspubsub.OpenSubscription`][] constructor opens a NATS subject as a
239 topic. You must first create an [`*nats.Conn`][] to your NATS instance.
240
241 {{< goexample "gocloud.dev/pubsub/natspubsub.ExampleOpenSubscription" >}}
242
243 [`*nats.Conn`]: https://godoc.org/github.com/nats-io/go-nats#Conn
244 [`natspubsub.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/natspubsub#OpenSubscription
245
246 ### Kafka {#kafka}
247
248 The Go CDK can receive messages from a [Kafka][] cluster.
249 A Kafka URL includes the consumer group name, plus at least one instance
250 of a query parameter specifying the topic to subscribe to.
251 The brokers in the Kafka cluster are discovered from the
252 `KAFKA_BROKERS` environment variable (which is a comma-delimited list of
253 hosts, something like `1.2.3.4:9092,5.6.7.8:9092`).
254
255 {{< goexample "gocloud.dev/pubsub/kafkapubsub.Example_openSubscriptionFromURL" >}}
256
257 [Kafka]: https://kafka.apache.org/
258
259 #### Kafka Constructor {#kafka-ctor}
260
261 The [`kafkapubsub.OpenSubscription`][] constructor creates a consumer in a
262 consumer group, subscribed to one or more topics.
263
264 In addition to the list of brokers, you'll need a [`*sarama.Config`][], which
265 exposes many knobs that can affect performance and semantics; review and set
266 them carefully. [`kafkapubsub.MinimalConfig`][] provides a minimal config to
267 get you started.
268
269 {{< goexample "gocloud.dev/pubsub/kafkapubsub.ExampleOpenSubscription" >}}
270
271 [`*sarama.Config`]: https://godoc.org/github.com/IBM/sarama#Config
272 [`kafkapubsub.OpenSubscription`]: https://godoc.org/gocloud.dev/pubsub/kafkapubsub#OpenSubscription
273 [`kafkapubsub.MinimalConfig`]: https://godoc.org/gocloud.dev/pubsub/kafkapubsub#MinimalConfig
274
275 ### In-Memory {#mem}
276
277 The Go CDK includes an in-memory Pub/Sub provider useful for local testing.
278 The names in `mem://` URLs are a process-wide namespace, so subscriptions to
279 the same name will receive messages posted to that topic. For instance, if
280 you open a topic `mem://topicA` and open two subscriptions with
281 `mem://topicA`, you will have two subscriptions to the same topic.
282
283 {{< goexample "gocloud.dev/pubsub/mempubsub.Example_openSubscriptionFromURL" >}}
284
285 #### In-Memory Constructor {#mem-ctor}
286
287 To create a subscription to an in-memory Pub/Sub topic, pass the [topic you
288 created][publish-mem-ctor] into the [`mempubsub.NewSubscription` function][].
289 You will also need to pass an acknowledgement deadline: once a message is
290 received, if it is not acknowledged after the deadline elapses, then it will be
291 redelivered.
292
293 {{< goexample "gocloud.dev/pubsub/mempubsub.ExampleNewSubscription" >}}
294
295 [`mempubsub.NewSubscription` function]: https://godoc.org/gocloud.dev/pubsub/mempubsub#NewSubscription
296 [publish-mem-ctor]: {{< ref "./publish.md#mem-ctor" >}}