pika

package module
v0.9.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2023 License: MIT Imports: 9 Imported by: 1

README

pika

A small RabbitMQ utility wrapper for go services

It provides a simpler abstraction to ease setting up services that communicate with RabbitMQ. To keep simplicity it makes a few assumptions:

  • There is only need for Topic Exchanges
  • Message body contains JSON
  • A Consumer only receives a message type

If you need more features consider a mixed used of the library or simply an alternative.

Connection

To connect to RabbitMQ create a new RabbitConnector

func main() {
  conn := pika.NewConnector()
  err := conn.Connect(RABBIT_URL)
  if err != nil {
    // TODO
  }
}

This connection will be reused for each Consumer, Publisher and Notifier (1 channel each).

If you have a more complex use-case you can still reuse the connection asking it for a new channel and setting up bindings yourself.

  channel, err := conn.Channel()

Consumer

To receive messages from RabbitMQ create a Consumer of the underlying event type.

type MsgEvent struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

type MsgConsumer struct {}

func (c MsgConsumer) Options() pika.ConsumerOptions {
  // TODO
}

func (c MsgConsumer) HandleMessage(e MsgEvent) error {
  return nil
}

Then start the consumer in you main file.

func main() {
    // ...

    err := pika.StartConsumer[MsgEvent](conn, MsgConsumer{})
    if err != nil {
        // TODO
    }
}
Consumer Options

The connector knows how to setup the connection based on the ConsumerOptions returned by the Consumer. At a minimum it needs an exchange, topic and queue.

func (c MsgConsumer) Options() pika.ConsumerOptions {
  return pika.NewConsumerOptions(
    "", // Exchange
    "", // Topic / Routing-Key
    "", // Queue name (leave empty for random name)
  )
}

To setup the queue to persist if the application crashes.

  return pika.NewConsumerOptions("", "", "").SetDurable()

This allows messages to queue-up and start consuming as soon as it starts

You can also retry messages. It will be done in memory instead of using a dead-letter exchange.

  return pika.NewConsumerOptions("", "", "").WithRetry(1, time.Second)

Publisher

A publisher is a simple abstraction to conform the event type. It only holds a channel.

publisher, err := pika.CreatePublisher[MsgEvent](conn, pika.PublisherOptions{
  Exchange: "",
  Topic: "",
})

// To use
publisher.Publish(MsgEvent{})

Notifier

Sometimes you want to perform operations on regular intervals and them publish the result.

type Notifier[T any] interface {
	Options() NotificationOptions
	Stop() bool
	Notify() (T, error)
}

PubSub

If for testing or other use-cases you don't want to connect to a rabbitMq cluster, You can a PubSub which will handle all communication in memory.

func main() {
    pubsub := pika.NewPubSub()

    publisher, _ := pika.CreatePublisher[MsgEvent](pubsub, PublisherOptions{"exchange", "topic"})
    
    pika.StartConsumer[MsgEvent](pubsub, YourConsumer{})

    // ....
}

As long as YourConsumer listens on the same exchange and topic it will receive every msg sent trough publisher.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendToTopic

func AppendToTopic(key, str string) string

func StartConsumer added in v0.6.1

func StartConsumer[T any](r Connector, consumer Consumer[T]) error

StartConsumer makes the necessary declarations and bindings to start a consumer. It will spawn 2 goroutines to receive and process (with retries) messages.

Everything will be handle with the options declared in the `Consumer` method `Options`

func StartNotifier added in v0.7.1

func StartNotifier[T any](r Connector, notifier Notifier[T]) error

StartNotifier initiates the `Notifier` that will run in a goroutine

Types

type AMQPChannel added in v0.9.1

type AMQPChannel struct {
	// contains filtered or unexported fields
}

Wraps an amqp.Channel to handle reconnects

func NewAMQPChannel added in v0.9.1

func NewAMQPChannel(conn *RabbitConnector) (*AMQPChannel, error)

func (*AMQPChannel) Ack added in v0.9.1

func (c *AMQPChannel) Ack(tag uint64, multiple bool)

func (*AMQPChannel) Close added in v0.9.4

func (c *AMQPChannel) Close() error

func (*AMQPChannel) Consume added in v0.9.1

func (c *AMQPChannel) Consume(opts ConsumerOptions, outMsgs chan any) error

func (*AMQPChannel) Logger added in v0.9.3

func (c *AMQPChannel) Logger() Logger

func (*AMQPChannel) Publish added in v0.9.1

func (c *AMQPChannel) Publish(opts PublisherOptions, msg []byte) error

func (*AMQPChannel) Reject added in v0.9.1

func (c *AMQPChannel) Reject(tag uint64, requeue bool)

type Channel added in v0.8.6

type Channel interface {
	Consume(ConsumerOptions, chan any) error
	Publish(PublisherOptions, []byte) error

	Ack(uint64, bool)
	Reject(uint64, bool)

	Logger() Logger
}

type Connector added in v0.9.1

type Connector interface {
	Connect(string) error
	Disconnect() error

	Channel() (Channel, error)

	SetLogger(Logger)
	Logger() Logger
}

func NewConnector

func NewConnector() Connector

func NewPubSub added in v0.9.1

func NewPubSub() Connector

type Consumer

type Consumer[T any] interface {
	Options() ConsumerOptions
	HandleMessage(T) error
}

Consumer represents a RabbitMQ consumer for a typed `T` message

type ConsumerOptions

type ConsumerOptions struct {
	Exchange  string
	Topic     string
	QueueName string
	// contains filtered or unexported fields
}

ConsumerOptions represents a queue binding for a Consumer

func NewConsumerOptions added in v0.5.2

func NewConsumerOptions(exchange, topic, queue string) ConsumerOptions

NewConsumerOptions creates a ConsumerOptions object with default configurations

func (ConsumerOptions) HasRetry added in v0.5.0

func (co ConsumerOptions) HasRetry() bool

func (ConsumerOptions) SetDurable added in v0.8.1

func (co ConsumerOptions) SetDurable() ConsumerOptions

SetDurable configures the queue to be persist if the consumer disconnects

func (ConsumerOptions) SetName added in v0.8.5

func (co ConsumerOptions) SetName(name string) ConsumerOptions

SetName sets the consumer name

func (ConsumerOptions) WithRetry added in v0.5.0

func (co ConsumerOptions) WithRetry(retries int, interval time.Duration) ConsumerOptions

WithRetry enables in memory retries of unhandled messages. It will retry `retries` times waiting `interval` each time.

type LogFunc added in v0.9.1

type LogFunc func(string)

type Logger added in v0.9.2

type Logger interface {
	Debug(...any)
	Info(...any)
	Warn(...any)
	Error(...any)
}

type Msg added in v0.8.4

type Msg[T any] struct {
	// contains filtered or unexported fields
}

Msg holds a RabbitMQ Delivery content's (after parse) alonside any attacked state needed. ex: number of retries

func (Msg[T]) Retry added in v0.8.5

func (msg Msg[T]) Retry(backoff time.Duration, msgs chan Msg[T])

Retry increases inner counter and sleeps before sending itself back through msgs.

func (Msg[T]) ShouldRetry added in v0.8.5

func (msg Msg[T]) ShouldRetry(retries int) bool

ShouldRetry reports if a msg can still be retried

type NotificationOptions

type NotificationOptions struct {
	Exchange string
	Topic    string
	Interval time.Duration
}

NotificationOptions represents the behaviour of the `Notifier`

type Notifier

type Notifier[T any] interface {
	Options() NotificationOptions
	Stop() bool
	Notify() (T, error)
}

Notifier is a `Publisher` that publish on a regular interval

type PubSub added in v0.9.1

type PubSub struct {
	// contains filtered or unexported fields
}

func (*PubSub) Channel added in v0.9.1

func (p *PubSub) Channel() (Channel, error)

func (*PubSub) Connect added in v0.9.1

func (p *PubSub) Connect(string) error

func (*PubSub) Disconnect added in v0.9.1

func (p *PubSub) Disconnect() error

func (*PubSub) Logger added in v0.9.3

func (p *PubSub) Logger() Logger

func (*PubSub) SetLogger added in v0.9.1

func (p *PubSub) SetLogger(l Logger)

type PubSubChannel added in v0.9.1

type PubSubChannel struct {
	// contains filtered or unexported fields
}

func (*PubSubChannel) Ack added in v0.9.1

func (p *PubSubChannel) Ack(uint64, bool)

func (*PubSubChannel) Consume added in v0.9.1

func (p *PubSubChannel) Consume(o ConsumerOptions, out chan any) error

func (*PubSubChannel) Logger added in v0.9.3

func (p *PubSubChannel) Logger() Logger

func (*PubSubChannel) Publish added in v0.9.1

func (p *PubSubChannel) Publish(o PublisherOptions, data []byte) error

func (*PubSubChannel) Reject added in v0.9.1

func (p *PubSubChannel) Reject(uint64, bool)

type Publisher

type Publisher[T any] struct {
	// contains filtered or unexported fields
}

Publisher represents a specific msg that can be published

func CreatePublisher added in v0.7.1

func CreatePublisher[T any](r Connector, options PublisherOptions) (*Publisher[T], error)

CreatePublisher creates a `Publisher`

func (Publisher[T]) Publish

func (p Publisher[T]) Publish(message T) error

Publish publishes the `message` on the specified exchange and queue

type PublisherOptions

type PublisherOptions struct {
	Exchange string
	Topic    string
}

PublisherOptions specifies where a Publisher will publish messages

type Queue

type Queue[T any] struct {
	// contains filtered or unexported fields
}

func NewQueue

func NewQueue[T any]() *Queue[T]

func (*Queue[T]) Dequeue

func (q *Queue[T]) Dequeue() *T

func (*Queue[T]) DequeueNoWait added in v0.5.1

func (q *Queue[T]) DequeueNoWait() *T

func (*Queue[T]) Length

func (q *Queue[T]) Length() int

func (*Queue[T]) PeakAt

func (q *Queue[T]) PeakAt(i int) *T

func (*Queue[T]) Peek

func (q *Queue[T]) Peek() *T

func (*Queue[T]) Queue

func (q *Queue[T]) Queue(e *T)

type RabbitConnector

type RabbitConnector struct {
	// contains filtered or unexported fields
}

func (*RabbitConnector) Channel

func (rc *RabbitConnector) Channel() (Channel, error)

func (*RabbitConnector) Connect

func (rc *RabbitConnector) Connect(url string) error

func (RabbitConnector) Disconnect

func (rc RabbitConnector) Disconnect() error

func (*RabbitConnector) Logger added in v0.9.3

func (rc *RabbitConnector) Logger() Logger

func (*RabbitConnector) SetLogger added in v0.9.1

func (rc *RabbitConnector) SetLogger(logger Logger)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL