github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/pubsub/amqp/topology_builder.go (about)

     1  package amqp
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  
     6  	"github.com/wfusion/gofusion/common/infra/watermill"
     7  
     8  	amqp "github.com/rabbitmq/amqp091-go"
     9  )
    10  
    11  // TopologyBuilder is responsible for declaring exchange, queues and queues binding.
    12  //
    13  // Default TopologyBuilder is DefaultTopologyBuilder.
    14  // If you need custom built topology, you should implement your own TopologyBuilder and pass it to the amqp.Config:
    15  //
    16  // 	config := NewDurablePubSubConfig()
    17  // 	config.TopologyBuilder = MyProCustomBuilder{}
    18  //
    19  //nolint: revive // interface too long issue
    20  type TopologyBuilder interface {
    21  	BuildTopology(channel *amqp.Channel, queueName string, exchangeName string, config Config, logger watermill.LoggerAdapter) error
    22  	ExchangeDeclare(channel *amqp.Channel, exchangeName string, config Config) error
    23  }
    24  
    25  type DefaultTopologyBuilder struct{}
    26  
    27  func (builder DefaultTopologyBuilder) ExchangeDeclare(channel *amqp.Channel, exchangeName string, config Config) error {
    28  	return channel.ExchangeDeclare(
    29  		exchangeName,
    30  		config.Exchange.Type,
    31  		config.Exchange.Durable,
    32  		config.Exchange.AutoDeleted,
    33  		config.Exchange.Internal,
    34  		config.Exchange.NoWait,
    35  		config.Exchange.Arguments,
    36  	)
    37  }
    38  
    39  func (builder *DefaultTopologyBuilder) BuildTopology(channel *amqp.Channel, queueName string,
    40  	exchangeName string, config Config, logger watermill.LoggerAdapter) error {
    41  	if _, err := channel.QueueDeclare(
    42  		queueName,
    43  		config.Queue.Durable,
    44  		config.Queue.AutoDelete,
    45  		config.Queue.Exclusive,
    46  		config.Queue.NoWait,
    47  		config.Queue.Arguments,
    48  	); err != nil {
    49  		return errors.Wrap(err, "cannot declare queue")
    50  	}
    51  
    52  	logger.Debug("[Common] watermill ampq queue declared", nil)
    53  
    54  	if exchangeName == "" {
    55  		logger.Debug("[Common] watermill ampq no exchange to declare", nil)
    56  		return nil
    57  	}
    58  	if err := builder.ExchangeDeclare(channel, exchangeName, config); err != nil {
    59  		return errors.Wrap(err, "cannot declare exchange")
    60  	}
    61  
    62  	logger.Debug("[Common] watermill ampq exchange declared", nil)
    63  
    64  	if err := channel.QueueBind(
    65  		queueName,
    66  		config.QueueBind.GenerateRoutingKey(queueName),
    67  		exchangeName,
    68  		config.QueueBind.NoWait,
    69  		config.QueueBind.Arguments,
    70  	); err != nil {
    71  		return errors.Wrap(err, "cannot bind queue")
    72  	}
    73  	return nil
    74  }