0


基于golang多消息队列中间件的封装nsq,rabbitmq,kafka

基于golang多消息队列中间件的封装nsq,rabbitmq,kafka

场景

在创建个人的公共方法库中有这样一个需求,就是不同的项目会用到不同的消息队列中间件,我的思路把所有的消息队列中间件进行封装一个消息队列接口(MQer)有两个方法一个生产一个消费,那么在实例化对象的时候根据配置文件指定当前项目使用的那个消息队列中间件;

接口模型

这个模型的核心思想是消息队列的核心功能生产者生产消息方法和消费者消费消息,任何消息队列都必须有这两个功能;根据如下代码消息队列中间件是可扩展的,只需在实例化消息队列对象那里添加新消息队列的实现;

  1. // MQer 消息队列接口type MQer interface{Producer(topic string, data []byte)Consumer(topic, channel string, ch chan[]byte, f func(b []byte))}// NewMQ 实例化消息队列对象funcNewMQ() MQer {switch conf.Conf.Default.Mq {// mq 设置的类型case"nsq":returnnew(MQNsqService)case"rabbit":returnnew(MQRabbitService)case"kafka":returnnew(MQKafkaService)default:returnnew(MQNsqService)}}/*
  2. 配置文件结构设计
  3. mqType: "" # nsq, rabbit, kafka 这三个值然当然了是可扩展的
  4. nsq:
  5. producer: ""
  6. consumer: ""
  7. rabbit:
  8. addr: ""
  9. user: ""
  10. password: ""
  11. kafka:
  12. addr: ""
  13. */

各个消息队列的实现

1. 依赖库
  • nsq : github.com/nsqio/go-nsq
  • rabbitmq : github.com/streadway/amqp
  • kafka : github.com/Shopify/sarama
2. nsq

nsq结构体

  1. // MQNsqService NSQ消息队列type MQNsqService struct{}

生产者

  1. // Producer 生产者func(m *MQNsqService)Producer(topic string, data []byte){
  2. nsqConf :=&nsq.Config{}
  3. client, err := nsq.NewProducer(nsqServer, nsqConf)if err !=nil{
  4. log.Error("[nsq]无法连接到队列")return}
  5. log.DebugF(fmt.Sprintf("[生产消息] topic : %s --> %s", topic,string(data)))
  6. err = client.Publish(topic, data)if err !=nil{
  7. log.Error("[生产消息] 失败 : "+ err.Error())}}

消费者

  1. var(
  2. nsqServer = conf.Conf.Default.Nsq.Producer // nsqServer)// Consumer 消费者func(m *MQNsqService)Consumer(topic, channel string, ch chan[]byte, f func(b []byte)){
  3. mh, err :=NewMessageHandler(nsqServer, channel)if err !=nil{
  4. log.Error(err)return}gofunc(){
  5. mh.SetMaxInFlight(1000)
  6. mh.Registry(topic, ch)}()gofunc(){for{select{case s :=<-ch:f(s)}}}()
  7. log.DebugF("[NSQ] ServerID:%v => %v started", channel, topic)}// MessageHandler MessageHandlertype MessageHandler struct{
  8. msgChan chan*goNsq.Message
  9. stop bool
  10. nsqServer string
  11. Channel string
  12. maxInFlight int}// NewMessageHandler return new MessageHandlerfuncNewMessageHandler(nsqServer string, channel string)(mh *MessageHandler, err error){if nsqServer ==""{
  13. err = fmt.Errorf("[NSQ] need nsq server")return}
  14. mh =&MessageHandler{
  15. msgChan:make(chan*goNsq.Message,1024),
  16. stop:false,
  17. nsqServer: nsqServer,
  18. Channel: channel,}return}// Registry register nsq topicfunc(m *MessageHandler)Registry(topic string, ch chan[]byte){
  19. config := goNsq.NewConfig()if m.maxInFlight >0{
  20. config.MaxInFlight = m.maxInFlight
  21. }
  22. consumer, err := goNsq.NewConsumer(topic, m.Channel, config)if err !=nil{panic(err)}
  23. consumer.SetLogger(nil,0)
  24. consumer.AddHandler(goNsq.HandlerFunc(m.handlerMessage))
  25. err = consumer.ConnectToNSQLookupd(m.nsqServer)if err !=nil{panic(err)}
  26. m.process(ch)}
  1. rabbitmq 结构体
  1. // MQRabbitService Rabbit消息队列type MQRabbitService struct{}

生产者

  1. // Producer 生产者func(m *MQRabbitService)Producer(topic string, data []byte){
  2. mq, err :=NewRabbitMQPubSub(topic)if err !=nil{
  3. log.Error("[rabbit]无法连接到队列")return}//defer mq.Destroy()
  4. log.DebugF(fmt.Sprintf("[生产消息] topic : %s --> %s", topic,string(data)))
  5. err = mq.PublishPub(data)if err !=nil{
  6. log.Error("[生产消息] 失败 : "+ err.Error())}}// NewRabbitMQPubSub 订阅模式创建 rabbitMq实例 (目前用的fanout模式)funcNewRabbitMQPubSub(exchangeName string)(*RabbitMQ,error){
  7. mq, err :=NewRabbitMQ("", exchangeName,"","")if mq ==nil|| err !=nil{returnnil, err
  8. }//获取connection
  9. mq.conn, err = amqp.Dial(mq.MqUrl)
  10. mq.failOnErr(err,"failed to connect mq!")if mq.conn ==nil|| err !=nil{returnnil, err
  11. }//获取channel
  12. mq.channel, err = mq.conn.Channel()
  13. mq.failOnErr(err,"failed to open a channel!")return mq, err
  14. }...其余代码见源码: https://github.com/mangenotwork/common/tree/main/mq

消费者

  1. // Consumer 消费者func(m *MQRabbitService)Consumer(topic, serverId string, ch chan[]byte, f func(b []byte)){
  2. mh, err :=NewRabbitMQPubSub(topic)if err !=nil{
  3. log.Error("[rabbit]无法连接到队列")return}
  4. msg := mh.RegistryReceiveSub()gofunc(m <-chan amqp.Delivery){for{select{case s :=<-m:f(s.Body)}}}(msg)
  5. log.DebugF("[Rabbit] ServerID:%v => %v started", serverId, topic)}// NewRabbitMQPubSub 订阅模式创建 rabbitMq实例 (目前用的fanout模式)funcNewRabbitMQPubSub(exchangeName string)(*RabbitMQ,error){
  6. mq, err :=NewRabbitMQ("", exchangeName,"","")if mq ==nil|| err !=nil{returnnil, err
  7. }//获取connection
  8. mq.conn, err = amqp.Dial(mq.MqUrl)
  9. mq.failOnErr(err,"failed to connect mq!")if mq.conn ==nil|| err !=nil{returnnil, err
  10. }//获取channel
  11. mq.channel, err = mq.conn.Channel()
  12. mq.failOnErr(err,"failed to open a channel!")return mq, err
  13. }... 其余代码见源码: https://github.com/mangenotwork/common/tree/main/mq
  1. kafka 结构体
  1. // MQKafkaService Kafka消息队列type MQKafkaService struct{}

生产者

  1. func(m *MQKafkaService)Producer(topic string, data []byte){
  2. config := sarama.NewConfig()
  3. config.Producer.RequiredAcks = sarama.WaitForAll // 发送完数据需要leader和follower都确认
  4. config.Producer.Partitioner = sarama.NewRandomPartitioner //写到随机分区中,我们默认设置32个分区
  5. config.Producer.Return.Successes =true// 成功交付的消息将在success channel返回// 构造一个消息
  6. msg :=&sarama.ProducerMessage{}
  7. msg.Topic = topic
  8. msg.Value = sarama.ByteEncoder(data)// 连接kafka
  9. client, err := sarama.NewSyncProducer(kafkaServer, config)if err !=nil{
  10. log.Error("Producer closed, err:", err)return}defer client.Close()// 发送消息
  11. pid, offset, err := client.SendMessage(msg)if err !=nil{
  12. log.Error("send msg failed, err:", err)return}
  13. log.InfoF("pid:%v offset:%v\n", pid, offset)}

消费者

  1. // Consumer 消费者
  2. func (m *MQKafkaService) Consumer(topic, serverId string, ch chan []byte, f func(b []byte)) {
  3. var wg sync.WaitGroup
  4. consumer, err := sarama.NewConsumer(kafkaServer, nil)
  5. if err != nil {
  6. log.ErrorF("Failed to start consumer: %s", err)
  7. return
  8. }
  9. partitionList, err := consumer.Partitions("task-status-data") // 通过topic获取到所有的分区
  10. if err != nil {
  11. log.Error("Failed to get the list of partition: ", err)
  12. return
  13. }
  14. log.Info(partitionList)
  15. for partition := range partitionList { // 遍历所有的分区
  16. pc, err := consumer.ConsumePartition(topic, int32(partition), sarama.OffsetNewest) // 针对每个分区创建一个分区消费者
  17. if err != nil {
  18. log.ErrorF("Failed to start consumer for partition %d: %s\n", partition, err)
  19. }
  20. wg.Add(1)
  21. go func(sarama.PartitionConsumer) { // 为每个分区开一个go协程取值
  22. for msg := range pc.Messages() { // 阻塞直到有值发送过来,然后再继续等待
  23. log.DebugF("Partition:%d, Offset:%d, key:%s, value:%s\n", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
  24. f(msg.Value)
  25. }
  26. defer pc.AsyncClose()
  27. wg.Done()
  28. }(pc)
  29. }
  30. wg.Wait()
  31. consumer.Close()
  32. }

总结

golang的接口是一种抽象类型,是对其他类型行为的概括与抽象,从语法角度来看,接口是一组方法定义的集合,文本的封装使用了golang接口这一特性,把所有的消息队列中间件抽象为一个MQer拥有生产和消费两个方法,具体的各个消息队列中间件去实现这两个方法即可,最明显的优点在于扩展性,解耦性,选择性,维护性这几个表象上。

完整代码

https://github.com/mangenotwork/common/tree/main/mq

你的星星是我分享的最大动力 : )


本文转载自: https://blog.csdn.net/Man_ge/article/details/132076442
版权归原作者 Man-Li 所有, 如有侵权,请联系我们删除。

“基于golang多消息队列中间件的封装nsq,rabbitmq,kafka”的评论:

还没有评论