脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - Go操作Kafka和Etcd方法详解

Go操作Kafka和Etcd方法详解

2022-09-02 15:10乔克 Golang

这篇文章主要为大家介绍了Go操作Kafka和Etcd方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

操作Kafka

Kafka 是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据,具有高性能、持久化、多副本备份、横向扩展等特点。本文介绍了如何使用 Go 语言发送和接收 kafka 消息。

sarama

Go 语言中连接 kafka 使用第三方库:github.com/Shopify/sar…

下载及安装

?
1
go get github.com/Shopify/sarama

注意事项

sarama v1.20 之后的版本加入了zstd压缩算法,需要用到 cgo,在 Windows 平台编译时会提示类似如下错误:

?
1
2
# github.com/DataDog/zstd
exec: "gcc":executable file not found in %PATH%

所以在 Windows 平台请使用 v1.19 版本的 sarama。

连接 kafka 发送消息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main
import (
    "fmt"
    "github.com/Shopify/sarama"
)
// 基于sarama第三方库开发的kafka client
func main() {
    config := sarama.NewConfig()
    config.Producer.RequiredAcks = sarama.WaitForAll          // 发送完数据需要leader和follow都确认
    config.Producer.Partitioner = sarama.NewRandomPartitioner // 新选出一个partition
    config.Producer.Return.Successes = true                   // 成功交付的消息将在success channel返回
    // 构造一个消息
    msg := &sarama.ProducerMessage{}
    msg.Topic = "web_log"
    msg.Value = sarama.StringEncoder("this is a test log")
    // 连接kafka
    client, err := sarama.NewSyncProducer([]string{"192.168.1.7:9092"}, config)
    if err != nil {
        fmt.Println("producer closed, err:", err)
        return
    }
    defer client.Close()
    // 发送消息
    pid, offset, err := client.SendMessage(msg)
    if err != nil {
        fmt.Println("send msg failed, err:", err)
        return
    }
    fmt.Printf("pid:%v offset:%v\n", pid, offset)
}

连接 kafka 消费消息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
    "fmt"
    "github.com/Shopify/sarama"
)
// kafka consumer
func main() {
    consumer, err := sarama.NewConsumer([]string{"127.0.0.1:9092"}, nil)
    if err != nil {
        fmt.Printf("fail to start consumer, err:%v\n", err)
        return
    }
    partitionList, err := consumer.Partitions("web_log") // 根据topic取到所有的分区
    if err != nil {
        fmt.Printf("fail to get list of partition:err%v\n", err)
        return
    }
    fmt.Println(partitionList)
    for partition := range partitionList { // 遍历所有的分区
        // 针对每个分区创建一个对应的分区消费者
        pc, err := consumer.ConsumePartition("web_log", int32(partition), sarama.OffsetNewest)
        if err != nil {
            fmt.Printf("failed to start consumer for partition %d,err:%v\n", partition, err)
            return
        }
        defer pc.AsyncClose()
        // 异步从每个分区消费信息
        go func(sarama.PartitionConsumer) {
            for msg := range pc.Messages() {
                fmt.Printf("Partition:%d Offset:%d Key:%v Value:%v", msg.Partition, msg.Offset, msg.Key, msg.Value)
            }
        }(pc)
    }
}

操作Etcd

这里使用官方的etcd/clientv3包来连接etcd并进行相关操作。

安装

?
1
go get go.etcd.io/etcd/clientv3

put和get操作

put命令用来设置键值对数据,get命令用来根据key获取值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
    "context"
    "fmt"
    "time"
    "go.etcd.io/etcd/clientv3"
)
func main(){
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"122.51.79.172:2379"},
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        // handle error!
        fmt.Printf("connect to etcd failed, err:%v\n", err)
        return
    }
    fmt.Println("connect to etcd success")
    defer cli.Close()
    // put
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    _, err = cli.Put(ctx, "coolops", "test")
    cancel()
    if err != nil {
        fmt.Printf("put to etcd failed, err:%v\n", err)
        return
    }
    // get
    ctx, cancel = context.WithTimeout(context.Background(), time.Second)
    resp, err := cli.Get(ctx, "coolops")
    cancel()
    if err != nil {
        fmt.Printf("get from etcd failed, err:%v\n", err)
        return
    }
    for _, ev := range resp.Kvs {
        fmt.Printf("%s:%s\n", ev.Key, ev.Value)
    }
}

watch操作

watch用来获取未来更改的通知。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main
import (
    "context"
    "fmt"
    "time"
    "go.etcd.io/etcd/clientv3"
)
func main(){
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"122.51.79.172:2379"},
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        // handle error!
        fmt.Printf("connect to etcd failed, err:%v\n", err)
        return
    }
    fmt.Println("connect to etcd success")
    defer cli.Close()
    // watch 操作,返回的是一个通道
    rch := cli.Watch(context.Background(), "coolops") // <-chan WatchResponse
    for wresp := range rch {
        for _, ev := range wresp.Events {
            fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
        }
    }
}

安装报错:

?
1
2
3
4
5
6
7
go: finding github.com/coreos/pkg latest
# github.com/coreos/etcd/clientv3/balancer/resolver/endpoint
E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\resolver\endpoint\endpoint.go:114:78: undefined: resolver.BuildOption
E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\resolver\endpoint\endpoint.go:182:31: undefined: resolver.ResolveNowOption
# github.com/coreos/etcd/clientv3/balancer/picker
E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\picker\err.go:37:44: undefined: balancer.PickOptions
E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\picker\roundrobin_balanced.go:55:54: undefined: balancer.PickOptions

解决: 将go.mod里的prpc改为1.26.0版本

?
1
google.golang.org/grpc v1.26.0

以上就是Go操作Kafka和Etcd方法详解的详细内容,更多关于Go操作Kafka Etcd的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/7129376877449314335

延伸 · 阅读

精彩推荐
  • Golang使用 go 实现多线程下载器的方法

    使用 go 实现多线程下载器的方法

    本篇文章带领大家学习使用go实现一个简单的多线程下载器,给她家详细介绍了多线程下载原理及实例代码,感兴趣的朋友跟随小编一起看看吧...

    qxcheng10452021-11-18
  • Golang使用go xorm来操作mysql的方法实例

    使用go xorm来操作mysql的方法实例

    今天小编就为大家分享一篇关于使用go xorm来操作mysql的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小...

    stpeace6602020-05-24
  • Golang如何有效控制 Go 线程数?

    如何有效控制 Go 线程数?

    前阵子,在读者交流群中有人提到 Go 默认设置的最大线程数的问题:如果超过一万个 G (挂载于 M 上)阻塞于系统调用,那么程序就会被挂掉。这是对的,因...

    Golang技术分享8722021-10-26
  • GolangGo语言实现顺序存储的线性表实例

    Go语言实现顺序存储的线性表实例

    这篇文章主要介绍了Go语言实现顺序存储的线性表的方法,实例分析了Go语言实现线性表的定义、插入、删除元素等的使用技巧,具有一定参考借鉴价值,需要的...

    OSC首席键客2872020-04-22
  • Golanggolang 如何通过反射创建新对象

    golang 如何通过反射创建新对象

    这篇文章主要介绍了golang 通过反射创建新对象的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    RuoiseHone8182021-06-06
  • Golanggolang实现跨域访问的方法

    golang实现跨域访问的方法

    这篇文章主要介绍了golang实现跨域访问的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    benben_20159422020-05-22
  • GolangGolang 正则匹配效率详解

    Golang 正则匹配效率详解

    这篇文章主要介绍了Golang 正则匹配效率详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    无痕空间10192021-05-29
  • GolangGO语言获取系统环境变量的方法

    GO语言获取系统环境变量的方法

    这篇文章主要介绍了GO语言获取系统环境变量的方法,实例分析了Getenv方法操作环境变量的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    niuniu7322020-04-19