1、下载sarama
go get github.com/Shopify/sarama
2、生产者
package main
import (
"fmt"
"github.com/Shopify/sarama"
)
func main(){
fmt.Println("Producer start send message...")
// 1、构建config对象,同时设置producer相关的参数
//获取Config对象
config := sarama.NewConfig()
// 生产者配置ACK
config.Producer.RequiredAcks = sarama.WaitForAll
//创建分区选择器,使用的是随机选择器(基于时间的一个随机算法)
config.Producer.Partitioner = sarama.NewRandomPartitioner
// 是否在消息发送成功之后把消费发送到Successes管道,默认是disable
config.Producer.Return.Successes = true
config.Producer.Return.Errors = true
// 2、构建连接对象
// 生成上最好把ip地址与程序主体分离
producer,error := sarama.NewAsyncProducer([]string{"192.168.43.15:9092"},config)
if error != nil{
fmt.Printf("build producer is faileld: %s",error.Error())
return
}
// 3、使用defer关闭producer
defer producer.AsyncClose()
// 4、构建发送的消息内容
value := "this is a test"
msg := &sarama.ProducerMessage{}
msg.Topic = "yjt"
msg.Value = sarama.ByteEncoder(value)
// 从终端接受输入,循环发送数据
//for{
// 接受数据到value
//fmt.Scanln(&value)
fmt.Printf("send mesage: %s
",value)
// 发送数据
// Input() 函数返回值是一个只写管道,chan<- *ProducerMessage
producer.Input() <- msg
select{
case succ := <- producer.Successes():
fmt.Printf("message %s send successed,offset is %d",value,succ.Offset)
case err := <- producer.Errors():
fmt.Printf("message %s send failed,error is %s",value,err.Err.Error())
//}
}
}
三、消费者
...