This is a simple implementation of an event bus in golang. Actually support follwing pattern:
- publish/subscribe
- request/response
To start use eventbus in your project, you can run the following command.
go get github.com/stanipetrosyan/go-eventbus
And import
import (
goeventbus "github.com/stanipetrosyan/go-eventbus"
)
Simple example of publish/subscribe pattern.
eventbus = goeventbus.NewEventBus()
address := "topic"
options := goeventbus.NewMessageHeadersBuilder().SetHeader("header", "value").Build()
message := goeventbus.NewMessageBuilder().SetPayload("Hi Topic").SetHeaders(options).Build()
eventbus.Channel(address).Subscriber().Listen(func(dc goeventbus.Context) {
fmt.Printf("Message %s\n", dc.Result().Data)
})
eventbus.Channel(address).Publisher().Publish(message)
Simple example of request/response pattern.
eventbus = goeventbus.NewEventBus()
address := "topic"
message := goeventbus.NewMessageBuilder().SetPayload("Hi Topic").Build()
eventbus.Channel(address).Subscriber().Listen(func(context goeventbus.Context) {
fmt.Printf("Message %s\n", context.Result().Extract())
context.Reply("Hello from subscriber")
})
eventbus.Channel(address).Publisher().Request(message, func(context goeventbus.Context) {
fmt.Printf("Message %s\n", context.Result().Extract())
})
For publishing, you need to create a Message object using this method.
message := goeventbus.NewMessageBuilder().SetPayload("Hi Topic").SetHeaders(options).Build()
Each message can have some options:
options := goeventbus.NewMessageHeadersBuilder().SetHeader("header", "value").Build()
message := goeventbus.NewMessageBuilder().setHeaders(options).Build()
eventBus.Channel("address").Publisher().Publish(message)
A processor works like a middleware, in fact forwards messages only if the predicate is satisfied. The method accepts a function with message and return must return a boolean.
eventbus.Channel("topic1").Processor(func(message goeventbus.Message) bool {
return message.Options.Headers().Contains("header")
})
A Network bus create a tcp connection between different services.
NetworkBus is a wrapper of local eventbus.
A simple server/client example is in examples/networkbus
directory.