19 tail和sarama模块使用

tail模块

下载

go get github.com/hpcloud/tail

使用

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/hpcloud/tail"
)

/*
type Config struct {
	// File-specifc
	Location    *SeekInfo // 在seek的位置开始读
	ReOpen      bool      // 重新打开重新创建的文件 (tail -F)
	MustExist   bool      // 如果文件不存在,则会提前失败,false则不会报错
	Poll        bool      // 轮询文件更改而不是使用 inotify
	Pipe        bool      // 命名管道 (mkfifo)
	RateLimiter *ratelimiter.LeakyBucket

	// Generic IO
	Follow      bool // 继续寻找新行 (tail -f)
	MaxLineSize int  // 如果非零,则将较长的行拆分为多行

	// Logger,当 nil 时,设置为 tail.DefaultLogger
	// 要禁用日志记录:将字段设置为 tail.DiscardingLogger
	Logger logger
}
*/

func checkErr(err error) {
	if err != nil {
		fmt.Println("ERROR:", err)
		os.Exit(1)
	}
}

//go get github.com/hpcloud/tail
func main() {
	fileName := "./test.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.Line
		ok   bool
	)
	for {
		line, ok = <-tails.Lines //遍历chan,读取日志内容
		if !ok {
			fmt.Printf("tail file close reopen, filename:%s\n", tails.Filename)
			time.Sleep(time.Second)
			continue
		}
		fmt.Println("line:", line.Text)
	}
}

运行程序,用记事本打开test.log文件并写入内容进行保存,下面显示结果:

2022/03/28 22:06:34 Seeked ./test.log - &{Offset:0 Whence:2}
line: hello
line: world

sarama模块

下载

go get github.com/Shopify/sarama

使用

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/Shopify/sarama"
)

//go get github.com/Shopify/sarama
//基于sarama第三方库开发kafka客户端
func main() {
	config := sarama.NewConfig()

	//NoResponse	不发送任何响应
	//WaitForLocal	只在响应之前等待本地提交成功
	//WaitForAll	响应之前等待所有同步副本提交
	config.Producer.RequiredAcks = sarama.WaitForAll //发送完数据需要leader和follow都确认

	config.Producer.Return.Successes = true                   //成功传递的消息将在成功通道上返回。
	config.Producer.Partitioner = sarama.NewRandomPartitioner //新选出一个分区

	//创建一个生产者,连接kafka
	client, err := sarama.NewSyncProducer([]string{"192.168.1.5:9092"}, config)
	if err != nil {
		panic(err)
	}
	defer client.Close()

	for {
		fmt.Print("->")
		reader := bufio.NewReader(os.Stdin)
		buf, err := reader.ReadString('\n')
		if err != nil {
			panic(err)
		}

		message := &sarama.ProducerMessage{Topic: "my_topic", Value: sarama.StringEncoder(buf)}
		_, _, err = client.SendMessage(message)
		if err != nil {
			panic(err)
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值