Golang SDK

Similar to the C++/Python SDK, the Golang SDK is also divided into two parts: Producer and Consumer. Here is an introduction to both.

Producer

First, import necessary packages:

  1. import (
  2. "github.com/apache/inlong/inlong-tubemq/tubemq-client-twins/tubemq-client-go/client"
  3. "github.com/apache/inlong/inlong-tubemq/tubemq-client-twins/tubemq-client-go/config"
  4. "github.com/apache/inlong/inlong-tubemq/tubemq-client-twins/tubemq-client-go/log"
  5. "github.com/apache/inlong/inlong-tubemq/tubemq-client-twins/tubemq-client-go/util"
  6. )

Then, set the producer’s configuration. In the following example, we access the local Master and subscribe to the topic demo_0:

  1. cfg, err := config.ParseAddress("127.0.0.1:8715?topic=demo_0")

If there are multiple topics, you can directly modify the Topics in the config:

  1. cfg.Producer.Topics = []string{"demo", "demo_0", "demo_1"}

After the configuration is completed, create a new instance of Producer. During this process, the SDK will register to the TubeMQ Master and send a heartbeat to get the metadata of the topic:

  1. p, err := client.NewProducer(cfg)

Then, construct and send the message:

  1. demoData := "hello_tubemq"
  2. msg := client.Message{
  3. Topic: cfg.Producer.Topics[topicIndex], // You can choose from the subscribed topic list
  4. Data: []byte(demoData),
  5. DataLen: int32(len(demoData)),
  6. }
  7. success, errCode, errMsg := p.SendMessage(&msg) // Send a message to TubeMQ, return whether it is successful, the error code, and the error message

Consumer

The Consumer is roughly the same as the Producer, except that there is the concept of a consumer group when setting the config:

  1. cfg, err := config.ParseAddress("127.0.0.1:8715?topic=demo_0&group=test_group")

Then, refer to the usage of the Producer to consume:

  1. c, err := client.NewConsumer(cfg) // Create a new Consumer instance
  2. cr, err := c.GetMessage() // Get message
  3. _, err = c.Confirm(cr.ConfirmContext, true) // Confirm to TubeMQ after getting the data

Example

The above content is a demo and ignores some details. For a complete and runnable example, please refer to Golang SDK Example.