是否有可能在sarama中创建kafka主题?我知道java API可以让你创建主题,但我找不到任何有关如何在sarama中执行此操作的信息.如果可能的话,我应该使用的示例或解释将非常感谢提前
Dan*_*cak 11
实际上,在较新版本的 Sarama 中,您可以使用ClusterAdmin创建主题。您可以在下面找到示例代码:
package main
import (
"github.com/Shopify/sarama" // Sarama 1.22.0
"log"
)
func main() {
brokerAddrs := []string{"localhost:9092"}
config := sarama.NewConfig()
config.Version = sarama.V2_1_0_0
admin, err := sarama.NewClusterAdmin(brokerAddrs, config)
if err != nil {
log.Fatal("Error while creating cluster admin: ", err.Error())
}
defer func() { _ = admin.Close() }()
err = admin.CreateTopic("topic.test.1", &sarama.TopicDetail{
NumPartitions: 1,
ReplicationFactor: 1,
}, false)
if err != nil {
log.Fatal("Error while creating topic: ", err.Error())
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:下面是一个仍然有效的旧答案,但此时 sarama 管理 api 正在开发中。从那时起,ClusterAdmin apis 取得了长足的进步,今天应该被视为解决这个问题的首选方法。如果您希望在 2020 年以上解决此问题,请参阅下面的其他 2 个答案。
可以使用 sarama 来管理 Kafka 中的主题。我正在编写一个用于管理 Kafka 主题的 terraform 提供程序,并使用 sarama 在后端进行繁重的工作。
您需要使用 sarama.Broker api 来执行此操作。例如
// Set broker configuration
broker := sarama.NewBroker("localhost:9092")
// Additional configurations. Check sarama doc for more info
config := sarama.NewConfig()
config.Version = sarama.V1_0_0_0
// Open broker connection with configs defined above
broker.Open(config)
// check if the connection was OK
connected, err := broker.Connected()
if err != nil {
log.Print(err.Error())
}
log.Print(connected)
// Setup the Topic details in CreateTopicRequest struct
topic := "blah25s"
topicDetail := &sarama.TopicDetail{}
topicDetail.NumPartitions = int32(1)
topicDetail.ReplicationFactor = int16(1)
topicDetail.ConfigEntries = make(map[string]*string)
topicDetails := make(map[string]*sarama.TopicDetail)
topicDetails[topic] = topicDetail
request := sarama.CreateTopicsRequest{
Timeout: time.Second * 15,
TopicDetails: topicDetails,
}
// Send request to Broker
response, err := broker.CreateTopics(&request)
// handle errors if any
if err != nil {
log.Printf("%#v", &err)
}
t := response.TopicErrors
for key, val := range t {
log.Printf("Key is %s", key)
log.Printf("Value is %#v", val.Err.Error())
log.Printf("Value3 is %#v", val.ErrMsg)
}
log.Printf("the response is %#v", response)
// close connection to broker
broker.Close()
Run Code Online (Sandbox Code Playgroud)
您可以在github 上查看工作代码。记得在运行代码之前启动kafka broker并导入所有golang依赖。
| 归档时间: |
|
| 查看次数: |
1975 次 |
| 最近记录: |