-
Notifications
You must be signed in to change notification settings - Fork 0
/
gochpubsub.go
107 lines (85 loc) · 1.82 KB
/
gochpubsub.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package goch
import (
"fmt"
"sync"
)
// This is a simple pubsub implementation using go channels
var lock = &sync.Mutex{}
// Agent is a simple pub/sub agent
type PubSubAgent struct {
mu sync.Mutex
subs map[string][]chan []byte
quit chan struct{}
closed bool
}
var SingleGoPubSubAgent *PubSubAgent
// NewAgent creates a new Agent as a singleton, we do not create new agents over and over again
func NewPubSubAgent() *PubSubAgent {
if SingleGoPubSubAgent == nil {
lock.Lock()
defer lock.Unlock()
if SingleGoPubSubAgent == nil {
fmt.Println("Creating single instance now.")
SingleGoPubSubAgent = &PubSubAgent{
subs: make(map[string][]chan []byte),
quit: make(chan struct{}),
}
} else {
fmt.Println("Single instance already created.")
}
} else {
fmt.Println("Single instance already created.")
}
return SingleGoPubSubAgent
}
// Publish publishes a message to a topic
func (b *PubSubAgent) Publish(topic string, msg []byte) {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return
}
for _, ch := range b.subs[topic] {
ch <- msg
}
}
// Subscribe subscribes to a topic
func (b *PubSubAgent) Subscribe(topic string) <-chan []byte {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return nil
}
ch := make(chan []byte, 100)
b.subs[topic] = append(b.subs[topic], ch)
return ch
}
// Close closes the agent
func (b *PubSubAgent) Close() {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return
}
b.closed = true
close(b.quit)
for _, ch := range b.subs {
for _, sub := range ch {
close(sub)
}
}
}
/*
func testme() {
// Create a new agent
agent := NewAgent()
// Subscribe to a topic
sub := agent.Subscribe("foo")
// Publish a message to the topic
go agent.Publish("foo", "hello world")
// Print the message
fmt.Println(<-sub)
// Close the agent
agent.Close()
}
*/