Initialize Pulsar Go client

To interact with Pulsar, you need a Client object first.

You can create a client object using the NewClient function, passing in a ClientOptions object.

Here’s an example:

  1. import (
  2. "log"
  3. "time"
  4. "github.com/apache/pulsar-client-go/pulsar"
  5. )
  6. func main() {
  7. client, err := pulsar.NewClient(pulsar.ClientOptions{
  8. URL: "pulsar://localhost:6650",
  9. OperationTimeout: 30 * time.Second,
  10. ConnectionTimeout: 30 * time.Second,
  11. })
  12. if err != nil {
  13. log.Fatalf("Could not instantiate Pulsar client: %v", err)
  14. }
  15. defer client.Close()
  16. }

If you have multiple brokers, you can initiate a client object as below.

  1. import (
  2. "log"
  3. "time"
  4. "github.com/apache/pulsar-client-go/pulsar"
  5. )
  6. func main() {
  7. client, err := pulsar.NewClient(pulsar.ClientOptions{
  8. URL: "pulsar://localhost:6650,localhost:6651,localhost:6652",
  9. OperationTimeout: 30 * time.Second,
  10. ConnectionTimeout: 30 * time.Second,
  11. })
  12. if err != nil {
  13. log.Fatalf("Could not instantiate Pulsar client: %v", err)
  14. }
  15. defer client.Close()
  16. }

For all configurable parameters, see ClientOptions.