Debian Codegraph @

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

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