gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/broker/broker.go (about)

     1  // Package broker is an interface used for asynchronous messaging
     2  package broker
     3  
     4  // Broker is an interface used for asynchronous messaging.
     5  type Broker interface {
     6  	Init(...Option) error
     7  	Options() Options
     8  	Address() string
     9  	Connect() error
    10  	Disconnect() error
    11  	Publish(topic string, m *Message, opts ...PublishOption) error
    12  	Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
    13  	String() string
    14  }
    15  
    16  // Handler is used to process messages via a subscription of a topic.
    17  // The handler is passed a publication interface which contains the
    18  // message and optional Ack method to acknowledge receipt of the message.
    19  type Handler func(Event) error
    20  
    21  type Message struct {
    22  	Header map[string]string
    23  	Body   []byte
    24  }
    25  
    26  // Event is given to a subscription handler for processing
    27  type Event interface {
    28  	Topic() string
    29  	Message() *Message
    30  	Ack() error
    31  }
    32  
    33  // Subscriber is a convenience return type for the Subscribe method
    34  type Subscriber interface {
    35  	Options() SubscribeOptions
    36  	Topic() string
    37  	Unsubscribe() error
    38  }
    39  
    40  var (
    41  	DefaultBroker Broker = newHttpBroker()
    42  )
    43  
    44  func NewBroker(opts ...Option) Broker {
    45  	return newHttpBroker(opts...)
    46  }
    47  
    48  func Init(opts ...Option) error {
    49  	return DefaultBroker.Init(opts...)
    50  }
    51  
    52  func Connect() error {
    53  	return DefaultBroker.Connect()
    54  }
    55  
    56  func Disconnect() error {
    57  	return DefaultBroker.Disconnect()
    58  }
    59  
    60  func Publish(topic string, msg *Message, opts ...PublishOption) error {
    61  	return DefaultBroker.Publish(topic, msg, opts...)
    62  }
    63  
    64  func Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
    65  	return DefaultBroker.Subscribe(topic, handler, opts...)
    66  }
    67  
    68  func String() string {
    69  	return DefaultBroker.String()
    70  }