gorabbitmq 笔记二 (确保消息成功发布到rabitmq)

 1. 确认消息成功发布到rabbitmq

SetConfirm函数
err :=  channel.Confirm(false)
if err != nil {
	log.Println("this.Channel.Confirm  ", err)
}
this.notifyConfirm = this.Channel.NotifyPublish(make(chan amqp.Confirmation))

这个函数会返回一个chan amqp.Confirmation的channel, 一般会把这个channel保存到自己实现的mq的结构体中,

type MQ struct {
    //这个channel就是conn.Channel()
	Channel *amqp.Channel   
    //确认发送到mq的channel
	notifyConfirm chan amqp.Confirmation
    //确认入列成功的channel
	notifyReturn  chan amqp.Return
}

确认消息监听函数, 启动一个协程,监听消息发送情况

func (this *MQ)ListenConfirm(){
    ret := <- this.notifyConfirm
    if ret.Ack{
	    log.Println("confirm:消息发送成功")
    } else{
        //这里表示消息发送到mq失败,可以处理失败流程
	    log.Println("confirm:消息发送失败")
    }
}

2. 确保消息入列成功

func (this *MQ)NotiryReturn(){
 	//前提需要设定Publish的mandatory为true
	this.notifyReturn=this.Channel.NotifyReturn(make(chan amqp.Return))
	go this.listenReturn() //使用协程执行
}

//消息是否正确入列
func (this *MQ)listenReturn(){
	ret:=<-this.notifyReturn
    //这里是OK使用延迟交换机, 如果没有使用延迟交换机去掉_, ok :=ret.Headers["x-delay"] 和 if中的ok
	_, ok :=ret.Headers["x-delay"]
	if string(ret.Body)!="" && !ok {
		log.Println("消息没有正确入列:", string(ret.Body))
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章