go语言操作rabbitMq

最近项目中需要用户自己传入exchange,routingKey,queue,由后端绑定exchange和routingKey到该queue。主要用到的包"github.com/streadway/amqp",该包提供了一些关于rabbitMq的操作

代码大概如下:

var amqpUrl = common.AMQPUrl
var conn *amqp.Connection
var channel *amqp.Channel
func SetupRMQ() (err error) {//该方法连接mqserver
   if channel == nil {
      conn, err = amqp.Dial(amqpUrl)//连接mqserver
      if err != nil {
         return err
      }

      channel, err = conn.Channel()//获得一个channel
      if err != nil {
         return err
      }
      beego.Debug("channel:", channel)
   }
   return nil
}
func PublishServiceMQ(serviceExchange,serviceRoutingKey,serviceQueue,serviceTypeId,msg string)error{//mqConfig的值可以传空,传空表示已经存在
   serviceExchange = strings.Trim(serviceExchange," ")
   serviceRoutingKey = strings.Trim(serviceRoutingKey," ")
   serviceQueue = strings.Trim(serviceQueue," ")
   if err := checkMQ(serviceExchange,serviceRoutingKey,serviceQueue); nil != err {
      beego.Error("非法MQ设置",err)
      return err
   }
   err = SetupRMQ()
   if nil != err {
      beego.Error("连接mq失败,",err)
      return err
   }
   beego.Debug("channel:", channel)
   err = channel.ExchangeDeclare(serviceExchange, "topic", true, false, false, true, nil)//声明exchange
   if nil != err {
      beego.Error("声明exchange失败,",err)
      return err
   }
   _,err = channel.QueueDeclare(serviceQueue, true, false, false, true, nil)//声明queue
   if nil != err {
      beego.Error("声明queue失败,",err)
      return err
   }
   err = channel.QueueBind(serviceQueue, serviceRoutingKey, serviceExchange, true, nil)
//绑定exchange,routingKey到queue
   if nil != err {
      beego.Error("绑定exchange失败,",err)
      return err
   }
   err = channel.Publish(serviceExchange, serviceRoutingKey, false, false, amqp.Publishing{//推送消息
      ContentType: "text/plain",
      Body:        []byte(msg),
   })
   return err
}

func checkMQ(serviceExchange,serviceRoutingKey,serviceQueue string) error{//由于项目的其他地方用到了mq,防止用户mq和我们的mq相同
   //先不校验其是否为空,添加时校验
   if serviceExchange == common.Exchange {
      beego.Error("非法exchange,不可使用,",serviceExchange)
      return errors.New("非法exchange,不可使用")
   }
   if strings.Contains(strings.ToLower(serviceRoutingKey),common.routingKey){
      beego.Error("非法routingKey,不可使用,",serviceRoutingKey)
      return errors.New("非法routingKey,不可使用")
   }
   if strings.Contains(strings.ToLower(serviceQueue),common.Queue){
      beego.Error("非法queue,不可使用,",serviceQueue)
      return errors.New("非法queue,不可使用")
   }
   return nil
}

你可能感兴趣的:(go语言操作rabbitMq)