【golang】kafka

这篇博客是用来记录用go安装及操作kafka库的时候踩到的坑~

安装kafka库

首先我参考了博客:https://blog.csdn.net/tflasd1157/article/details/81985722https://blog.csdn.net/u011596455/article/details/80073841

在go get github.com/Shopify/sarama安装过程中出现了

package golang.org/x/net/proxy: unrecognized import path "golang.org/x/net/proxy" (https fetch: Get https://golang.org/x/net/proxy?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

起初我以为是被墙了的原因,后来借用同学的ssrr节点FQ后还是没能解决。

直到我看到这篇博客:https://www.jianshu.com/p/a55ba2ae6507

go get的时候遇到这个unrecognized import path "golang.org/x/net/html"提示,因为golang被大清墙了。
因此我们只能从github上拿到这部分包,放入项目中。

命令:
git clone https://github.com/golang/net
也可手动下载后解压
在gopath目录的src文件夹内建立如下目录 golang.org/x/net,将上面下载的net里面的文件放到该net目录中即可!

随后继续go get,然后又是报这个错。。

# github.com/DataDog/zstd
cc1.exe: sorry, unimplemented: 64-bit mode not compiled in

意思是mingw需要下载64位版本,而系统自带的是32位,所以又参考惹这篇博客安装mingw64:https://www.cnblogs.com/ggg-327931457/p/9694516.html

安装之前的gcc版本

 

还没安装又弹出个错误

折腾了半天试了各种方法还是不好使最后结果把校园网换成热点竟然成了。。成了。。。。

 安装好之后修改配置变量,把其他所有有关mingw配置全删了,替换成刚下载的mingw64/bin

 

继续执行go get github.com/Shopify/sarama

顺利安装成功~

go操作kafka

首先启动zookeeper和kafka

创建了一个main.go

package main

import (
    "fmt"

    "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 = "test"//topic没有的话会新建
    msg.Value = sarama.StringEncoder("this is a good test,my message is zhaofan")
    client, err := sarama.NewSyncProducer([]string{"192.168.0.118:9092"}, config)
    if err != nil {
        fmt.Println("producer close err:", err)
        return
    }
    defer client.Close()

    pid, offset, err := client.SendMessage(msg)
    if err != nil {
        fmt.Println("send message failed,", err)
        return
    }
    fmt.Printf("pid:%v offset:%v\n", pid, offset)
}

go run main.go后消费者执行

kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --from-beginning

成功

 

posted @ 2019-04-17 09:38  LesRoad  阅读(2683)  评论(2编辑  收藏  举报