1 Star 0 Fork 0

yzsunjianguo / sponge

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
publisher.go 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
yzsunjianguo 提交于 2024-02-08 14:53 . init
package rabbitmq
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
"go.uber.org/zap"
)
// Publisher session
type Publisher struct {
*Producer
}
// NewPublisher create a publisher, channelName is exchange name
func NewPublisher(channelName string, connection *Connection, opts ...ProducerOption) (*Publisher, error) {
o := defaultProducerOptions()
o.apply(opts...)
exchange := NewFanoutExchange(channelName)
// crate a new channel
ch, err := connection.conn.Channel()
if err != nil {
return nil, err
}
// declare the exchange type
err = ch.ExchangeDeclare(
channelName,
exchangeTypeFanout,
o.isPersistent,
o.exchangeDeclare.autoDelete,
o.exchangeDeclare.internal,
o.exchangeDeclare.noWait,
o.exchangeDeclare.args,
)
if err != nil {
_ = ch.Close()
return nil, err
}
deliveryMode := amqp.Persistent
if !o.isPersistent {
deliveryMode = amqp.Transient
}
connection.zapLog.Info("[rabbit producer] initialized", zap.String("channel", channelName), zap.Bool("isPersistent", o.isPersistent))
p := &Producer{
Exchange: exchange,
conn: connection.conn,
ch: ch,
isPersistent: o.isPersistent,
deliveryMode: deliveryMode,
mandatory: o.mandatory,
zapLog: connection.zapLog,
}
return &Publisher{p}, nil
}
func (p *Publisher) Publish(ctx context.Context, body []byte) error {
return p.ch.PublishWithContext(
ctx,
p.Exchange.name,
p.Exchange.routingKey,
p.mandatory,
false,
amqp.Publishing{
DeliveryMode: p.deliveryMode,
ContentType: "text/plain",
Body: body,
},
)
}
// Close publisher
func (p *Publisher) Close() {
if p.ch != nil {
_ = p.ch.Close()
}
}
Go
1
https://gitee.com/yzsunjianguo/sponge.git
git@gitee.com:yzsunjianguo/sponge.git
yzsunjianguo
sponge
sponge
v1.0.3

搜索帮助