2015-04-26 19:33:35 +01:00
|
|
|
package broker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"code.google.com/p/go-uuid/uuid"
|
2015-05-23 23:16:26 +01:00
|
|
|
"golang.org/x/net/context"
|
2015-04-26 19:33:35 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type Broker interface {
|
|
|
|
Address() string
|
|
|
|
Connect() error
|
|
|
|
Disconnect() error
|
|
|
|
Init() error
|
2015-05-23 23:16:26 +01:00
|
|
|
Publish(context.Context, string, []byte) error
|
|
|
|
Subscribe(string, func(context.Context, *Message)) (Subscriber, error)
|
2015-04-26 19:33:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type Message struct {
|
|
|
|
Id string
|
|
|
|
Timestamp int64
|
|
|
|
Topic string
|
2015-05-23 23:16:26 +01:00
|
|
|
Body []byte
|
2015-04-26 19:33:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type Subscriber interface {
|
|
|
|
Topic() string
|
|
|
|
Unsubscribe() error
|
|
|
|
}
|
|
|
|
|
2015-05-16 00:34:02 +01:00
|
|
|
type options struct{}
|
|
|
|
|
2015-05-23 20:04:16 +01:00
|
|
|
type Option func(*options)
|
2015-05-16 00:34:02 +01:00
|
|
|
|
2015-04-26 19:33:35 +01:00
|
|
|
var (
|
|
|
|
Address string
|
|
|
|
Id string
|
|
|
|
DefaultBroker Broker
|
|
|
|
)
|
|
|
|
|
2015-05-23 20:04:16 +01:00
|
|
|
func NewBroker(addrs []string, opt ...Option) Broker {
|
|
|
|
return newHttpBroker([]string{Address}, opt...)
|
|
|
|
}
|
|
|
|
|
2015-04-26 19:33:35 +01:00
|
|
|
func Init() error {
|
|
|
|
if len(Id) == 0 {
|
|
|
|
Id = "broker-" + uuid.NewUUID().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
if DefaultBroker == nil {
|
2015-05-23 20:04:16 +01:00
|
|
|
DefaultBroker = newHttpBroker([]string{Address})
|
2015-04-26 19:33:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return DefaultBroker.Init()
|
|
|
|
}
|
|
|
|
|
|
|
|
func Connect() error {
|
|
|
|
return DefaultBroker.Connect()
|
|
|
|
}
|
|
|
|
|
|
|
|
func Disconnect() error {
|
|
|
|
return DefaultBroker.Disconnect()
|
|
|
|
}
|
|
|
|
|
2015-05-23 23:16:26 +01:00
|
|
|
func Publish(ctx context.Context, topic string, body []byte) error {
|
|
|
|
return DefaultBroker.Publish(ctx, topic, body)
|
2015-04-26 19:33:35 +01:00
|
|
|
}
|
|
|
|
|
2015-05-23 23:16:26 +01:00
|
|
|
func Subscribe(topic string, function func(context.Context, *Message)) (Subscriber, error) {
|
2015-04-26 19:33:35 +01:00
|
|
|
return DefaultBroker.Subscribe(topic, function)
|
|
|
|
}
|