forked from kyma-project/kyma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.go
71 lines (60 loc) · 1.9 KB
/
nats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package controllers
import (
"log"
"time"
ns "github.com/kyma-project/kyma/components/event-bus/internal/stanutil"
stan "github.com/nats-io/go-nats-streaming"
)
const (
numPollers = 2 // number of Poller goroutines to launch
statusInterval = 10 * time.Second // how often to log status to stdout
)
//TODO Add reconnect logic
// Publisher sends a message to a specific topic
type Publisher interface {
Start() error
Stop() error
Publish(subject, message string) error
IsReady() (bool, error)
}
// streamingController is a NATS Streaming Controller that handles all communication aspects with NATS.
// It is also responsible of the NATS connection management.
type streamingController struct {
clientID string
natsURL string
clusterID string
natsConn *stan.Conn
}
// Start Start the NATS Streaming controller
func (sc *streamingController) Start() error {
var err error
if sc.natsConn, err = ns.Connect(sc.clusterID, sc.clientID, sc.natsURL); err != nil {
log.Printf(" Create new connection failed: %+v", err)
return err
}
return nil
}
// Stop Stop the Streaming Controller and close the NATS connection
func (sc *streamingController) Stop() error {
return ns.Close(sc.natsConn)
}
// Publish sends a message to NATS
func (sc *streamingController) Publish(subject, message string) error {
messageArray := []byte(message)
if err := ns.Publish(sc.natsConn, subject, &messageArray); err != nil {
log.Printf(" Failed to publish message to NATS Streaming: %+v", err)
return err
}
return nil
}
func (sc *streamingController) IsReady() (bool, error) {
return ns.IsConnected(sc.natsConn), nil
}
//GetPublisher Factory function to created and return a new Publisher instance
func GetPublisher(clientID, natsURL, clusterID string) Publisher {
publisher := streamingController{}
publisher.clientID = clientID
publisher.natsURL = natsURL
publisher.clusterID = clusterID
return &publisher
}