@@ -2,6 +2,7 @@ package rabbitmq
2
2
3
3
import (
4
4
"context"
5
+ "fmt"
5
6
6
7
amqp "github.com/rabbitmq/amqp091-go"
7
8
"go.uber.org/zap"
@@ -25,6 +26,15 @@ func NewPublisher(channelName string, connection *Connection, opts ...ProducerOp
25
26
return nil , err
26
27
}
27
28
29
+ // enable publisher confirm
30
+ if o .isPublisherConfirm {
31
+ err = ch .Confirm (false )
32
+ if err != nil {
33
+ _ = ch .Close ()
34
+ return nil , err
35
+ }
36
+ }
37
+
28
38
// declare the exchange type
29
39
err = ch .ExchangeDeclare (
30
40
channelName ,
@@ -61,7 +71,7 @@ func NewPublisher(channelName string, connection *Connection, opts ...ProducerOp
61
71
}
62
72
63
73
func (p * Publisher ) Publish (ctx context.Context , body []byte ) error {
64
- return p .ch .PublishWithContext (
74
+ err := p .ch .PublishWithContext (
65
75
ctx ,
66
76
p .Exchange .name ,
67
77
p .Exchange .routingKey ,
@@ -73,6 +83,24 @@ func (p *Publisher) Publish(ctx context.Context, body []byte) error {
73
83
Body : body ,
74
84
},
75
85
)
86
+ if err != nil {
87
+ return err
88
+ }
89
+
90
+ if p .isPublisherConfirm {
91
+ // wait for publisher confirm
92
+ select {
93
+ case <- ctx .Done ():
94
+ return ctx .Err ()
95
+ case confirm := <- p .ch .NotifyPublish (make (chan amqp.Confirmation , 1 )):
96
+ if ! confirm .Ack {
97
+ return fmt .Errorf ("publisher confirm failed, exchangeName: %s, routingKey: %s, deliveryTag: %d" ,
98
+ p .Exchange .name , p .Exchange .routingKey , confirm .DeliveryTag )
99
+ }
100
+ }
101
+ }
102
+
103
+ return nil
76
104
}
77
105
78
106
// Close publisher
0 commit comments