-
Notifications
You must be signed in to change notification settings - Fork 0
/
subject_publisher.go
53 lines (50 loc) · 1.38 KB
/
subject_publisher.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
package nats
import (
"context"
"github.com/nats-io/nats.go"
)
type SubjectPublisher struct {
Conn *nats.Conn
}
func NewSubjectPublisher(conn *nats.Conn) *SubjectPublisher {
return &SubjectPublisher{conn}
}
func NewSubjectPublisherByConfig(p PublisherConfig) (*SubjectPublisher, error) {
if p.Connection.Retry.Retry1 <= 0 {
conn, err := nats.Connect(p.Connection.Url, p.Connection.Option)
if err != nil {
return nil, err
}
return NewSubjectPublisher(conn), nil
} else {
durations := DurationsFromValue(p.Connection.Retry, "Retry", 9)
conn, err := NewConn(durations, p.Connection.Url, p.Connection.Option)
if err != nil {
return nil, err
}
return NewSubjectPublisher(conn), nil
}
}
func (p *SubjectPublisher) Publish(ctx context.Context, subject string, data []byte, attributes map[string]string) error {
defer p.Conn.Flush()
if attributes == nil {
return p.Conn.Publish(subject, data)
} else {
header := MapToHeader(attributes)
var msg = &nats.Msg{
Subject: subject,
Data: data,
Reply: "",
Header: nats.Header(*header),
}
return p.Conn.PublishMsg(msg)
}
}
func (p *SubjectPublisher) PublishData(ctx context.Context, subject string, data []byte) error {
defer p.Conn.Flush()
return p.Conn.Publish(subject, data)
}
func (p *SubjectPublisher) PublishMsg(subject string, data []byte) error {
defer p.Conn.Flush()
return p.Conn.Publish(subject, data)
}