验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

golang怎么连接kafka

阅读:1140 来源:乙速云 作者:代码code

golang怎么连接kafka

      1 下载,配置,启动 kafka

      配置修改

      在config目录下的server文件和zookeeper文件,其中分别修改kafka的日志保存路径和zookeeper的数据保存路径。

      golang怎么连接kafka

      启动kafka

      先启动kafka自带的zookeeper,在kafka的根目录下打开终端,使用配置文件启动

      ./bin/windows/zookeeper-server-start.bat config/zookeeper.properties

      同样在kafka目录的根目录下启动kafka

      ./bin/windows/kafka-server-start.bat config/server.properties

      2 使用golang的github.com/Shopify/sarama库连接kafka

      package main
      
      import (
      	"fmt"
      	"time"
      
      	"github.com/Shopify/sarama"
      )
      
      func main() {
      	config:=sarama.NewConfig()
      	// 生产者配置
      	config.Producer.RequiredAcks=sarama.WaitForAll
      	config.Producer.Partitioner=sarama.NewRandomPartitioner
      	config.Producer.Return.Successes=true
      	// 封装消息
      	msg:=&sarama.ProducerMessage{}
      	msg.Topic="shopping"
      	time_str:=time.Now().Format("2006-01-02 15:04:05")
      	msg.Value=sarama.StringEncoder("0413 test log!"+time_str)
      	// 连接kafka
      	client,err:=sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config)
      	if err!=nil {
      		fmt.Println("producer closed", err)
      		return
      	}
      	defer client.Close()
      	// 发送消息
      	partition,offset,err:=client.SendMessage(msg)
      	if err!=nil {
      		fmt.Println("send failed", err)
      		return
      	}
      	fmt.Printf("partition:%v offset:%v", partition, offset)
      }

      这段代码实现了模拟生产者向kafka发送消息的过程,包含:配置生产者,封装消息,消息类型是 *sarama.ProducerMessage,连接kafka,默认端口是9092,发送消息,返回消息存储的partition和offset日志偏移量。

      3 确认生产者发送成功

      使用kafka自带的命令行消费者客户端查看kafka中的数据
      在kafka的根目录下

      bin/windows/kafka-console-consumer.bat --bootstrap-server 127.0.0.1:9092 --topic shopping --from-beginning

      这里的topic和代码中的topic一致,均为shopping
      终端会输出之前发送的数据。

    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>