- Go
- Tutorial
Build Producer
Let's create the producer application by pasting the following Go code into a file named producer.go
.
package main
import (
"context"
"fmt"
"math/rand"
"os"
"github.com/apache/pulsar-client-go/pulsar"
)
func main() {
client, err := pulsar.NewClient(pulsar.ClientOptions{
URL: "<Broker Service URL>",
Authentication: pulsar.NewAuthenticationToken("<API KEY>"),
})
if err != nil {
fmt.Printf("Failed to create Pulsar client: %s", err)
os.Exit(1)
}
users := [...]string{"eabara", "jsmith", "sgarcia", "jbernard", "htanaka", "awalther"}
items := [...]string{"book", "alarm clock", "t-shirts", "gift card", "batteries"}
topic := "purchases"
producer, err := client.CreateProducer(pulsar.ProducerOptions{
Topic: topic,
})
if err != nil {
fmt.Printf("Failed to create Pulsar producer: %s", err)
os.Exit(1)
}
defer producer.Close()
for n := 0; n < 10; n++ {
key := users[rand.Intn(len(users))]
data := items[rand.Intn(len(items))]
if msgId, err := producer.Send(context.Background(), &pulsar.ProducerMessage{
Key: key,
Payload: []byte(data),
}); err != nil {
fmt.Printf("Failed to deliver message: %s", err)
} else {
fmt.Printf("Produced event to topic: ID = %s, key = %-10s value = %s\n", msgId, key, data)
}
}
}
Fill in the appropriate <Broker Service URL>
endpoint and <API KEY>
in the URL
and Authentication
properties where the producer is instantiated using the pulsar.NewClient
method.
Compile the producer with the following:
go build -o out/producer producer.go
If you get any errors during the build make sure that you initialized the module correctly per the instructions in the previous step.