2015-04-26 21:33:35 +03:00
|
|
|
package broker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2015-05-16 02:34:02 +03:00
|
|
|
"strings"
|
2015-04-26 21:33:35 +03:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"code.google.com/p/go-uuid/uuid"
|
|
|
|
"github.com/apcera/nats"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NatsBroker struct {
|
2015-05-16 02:34:02 +03:00
|
|
|
addrs []string
|
|
|
|
conn *nats.Conn
|
2015-04-26 21:33:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
type NatsSubscriber struct {
|
|
|
|
s *nats.Subscription
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsSubscriber) Topic() string {
|
|
|
|
return n.s.Subject
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsSubscriber) Unsubscribe() error {
|
|
|
|
return n.s.Unsubscribe()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Address() string {
|
2015-05-16 02:34:02 +03:00
|
|
|
if len(n.addrs) > 0 {
|
|
|
|
return n.addrs[0]
|
|
|
|
}
|
|
|
|
return ""
|
2015-04-26 21:33:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Connect() error {
|
|
|
|
if n.conn != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-05-16 02:34:02 +03:00
|
|
|
opts := nats.DefaultOptions
|
|
|
|
opts.Servers = n.addrs
|
|
|
|
c, err := opts.Connect()
|
2015-04-26 21:33:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
n.conn = c
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Disconnect() error {
|
|
|
|
n.conn.Close()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Init() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Publish(topic string, data []byte) error {
|
|
|
|
b, err := json.Marshal(&Message{
|
|
|
|
Id: uuid.NewUUID().String(),
|
|
|
|
Timestamp: time.Now().Unix(),
|
|
|
|
Topic: topic,
|
|
|
|
Data: data,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return n.conn.Publish(topic, b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *NatsBroker) Subscribe(topic string, function func(*Message)) (Subscriber, error) {
|
|
|
|
subscriber, err := n.conn.Subscribe(topic, func(msg *nats.Msg) {
|
|
|
|
var data *Message
|
|
|
|
if err := json.Unmarshal(msg.Data, &data); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
function(data)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &NatsSubscriber{s: subscriber}, nil
|
|
|
|
}
|
|
|
|
|
2015-05-16 02:34:02 +03:00
|
|
|
func NewNatsBroker(addrs []string, opts ...Options) Broker {
|
|
|
|
if len(addrs) == 0 {
|
|
|
|
addrs = []string{nats.DefaultURL}
|
|
|
|
}
|
|
|
|
for i, addr := range addrs {
|
|
|
|
if !strings.HasPrefix(addr, "nats://") {
|
|
|
|
addrs[i] = "nats://" + addr
|
|
|
|
}
|
|
|
|
}
|
2015-04-26 21:33:35 +03:00
|
|
|
return &NatsBroker{
|
2015-05-16 02:34:02 +03:00
|
|
|
addrs: addrs,
|
2015-04-26 21:33:35 +03:00
|
|
|
}
|
|
|
|
}
|