711 字
4 分钟
day11课上笔记
day11课上笔记
今日内容
依赖管理go module
如果是使用的Go1.11和Go1.12的版本,需要手动开启go module支持:

goproxy
设置代理,下载墙外的库更快、
export GOPROXY=https://goproxy.cn Mac
SET GOPROXY=https://goproxy.cn Windowsgo.mod文件
记录了当前项目依赖的第三方包信息和版本信息
第三方的依赖包都下载到了 GOPATH/pkg/mod目录下。
go.sum文件
详细包名和版本信息
常用的命令
go mod init [包名] // 初始化项目go mod tidy // 检查代码里的依赖去更新go.mod文件中的依赖go getgo mod downloadContext
非常重要!
如何优雅的控制子goroutine退出?
两个默认值
context.Background()context.TODO()四个方法
context.WithCancel(context.Background())context.WithDeadline(context.Background(), time.Time)context.WithTimeout(context.Background(), time.Duration)context.WithValue(context.BackGround(), key, value)服务端Agent开发
zookkeeper、kafka部署文档:https://docs.qq.com/doc/DTmdldEJJVGtTRkFi
Kafka

-
Kafka集群的架构
- broker
- topic
- partition:分区,把同一个topic分成不同的分区,提高负载
- leader:分区的主节点(老大)
- follower:分区的从节点(小弟)
- Consumer Group
-
生产者往Kafka发送数据的流程(6步)

-
Kafka选择分区的模式(3种)
- 指定往哪个分区写
- 指定key,kafka根据key做hash然后决定写哪个分区
- 轮询方式
-
生产者往kafka发送数据的模式(3种)
0:把数据发给leader就成功,效率最高、安全性最低。1: 把数据发送给leader,等待leader回ACKall:把数据发给leader,确保follower从leader拉取数据回复ack给leader,leader再回复ACK;安全性最高
-
分区存储文件的原理
-
为什么kafka快?
-
消费者组消费数据的原理
项目架构设计

LogAgent的工作流程:
-
读日志 —
tailf第三方库func main() {fileName := "./my.log"config := tail.Config{ReOpen: true, // 重新打开Follow: true, // 是否跟随Location: &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读MustExist: false, // 文件不存在不报错Poll: true,}tails, err := tail.TailFile(fileName, config)if err != nil {fmt.Println("tail file failed, err:", err)return}var (line *tail.Lineok bool)for {line, ok = <-tails.Linesif !ok {fmt.Printf("tail file close reopen, filename:%s\n", tails.Filename)time.Sleep(time.Second)continue}fmt.Println("line:", line.Text)}} -
往kafka写日志 —
sarama第三方库// 基于sarama第三⽅库开发的kafka clientfunc main() {config := sarama.NewConfig()// tailf包使⽤config.Producer.RequiredAcks = sarama.WaitForAll // 发送完数据需要leader和follow都确认config.Producer.Partitioner = sarama.NewRandomPartitioner // 新选出⼀个 partitionconfig.Producer.Return.Successes = true // 成功交付的消息将在success channel返回// 构造⼀个消息msg := &sarama.ProducerMessage{}msg.Topic = "web_log"msg.Value = sarama.StringEncoder("this is a test log")// 连接kafkaclient, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config)if err != nil {fmt.Println("producer closed, err:", err)return}fmt.Println("连接kafka成功!")defer client.Close()// 发送消息pid, offset, err := client.SendMessage(msg)fmt.Println("xxx")if err != nil {fmt.Println("send msg failed, err:", err)return}fmt.Printf("pid:%v offset:%v\n", pid, offset)fmt.Println("发送成功!")}
kafka和zookeeper
tail介绍
gopkg.in/ini.v1
kafka终端读取数据:
bin\windows\kafka-console-consumer.bat --bootstrap-server=127.0.0.1:9092 --topic=web_log --from-beginning补充
Goland开启go module和设置GOPROXY代理

本周作业
把logagent自己实现一遍