Simple worker based publish/subscribe style communication between Go components.
Example:
package main
import (
"fmt"
"sync"
. "github.com/larsp/bus"
)
type SomeEvent struct {
Message string
WG *sync.WaitGroup
}
func SomeEventHandler(event SomeEvent) {
fmt.Println(event.Message)
event.WG.Done()
}
func main() {
bus := New(10, 2) // channel can buffer 10 events and 2 workers consume from that channel
var wg sync.WaitGroup
wg.Add(1)
bus.Register(SomeEventHandler)
bus.Publish(SomeEvent{"Hallo!", &wg})
wg.Wait() // Waiting for the handler to process the event
}
type EventBus interface {
// Register an event handler Register(function interface{}, forTypes ...interface{}) error// Publish will push the passed event to a channel. If that channel is full this method will block.// In order to avoid blocking the user could wrap Publish into a goroutine.
Publish(event interface{}) error
}
EventBus interfaces declares supported methods for registering an handle and publishing to the bus
New creates a new bus instances. Given your workload you need to specify the following parameters:
queueSize is used in order to create a channel with given size.
workers creates as many workers to process events from the channel.