-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (85 loc) · 2.01 KB
/
main.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
package main
import (
"fmt"
"sync"
"time"
)
type Message struct {
Topic string
Payload interface{}
}
type Subscriber struct {
Channel chan interface{}
Unsubscribe chan bool
}
type Broker struct {
subscribers map[string][]*Subscriber
mutex sync.Mutex
}
func NewBroker() *Broker {
return &Broker{
subscribers: make(map[string][]*Subscriber),
}
}
func (b *Broker) Subscribe(topic string) *Subscriber {
b.mutex.Lock()
defer b.mutex.Unlock()
subscriber := &Subscriber{
Channel: make(chan interface{}, 1),
Unsubscribe: make(chan bool),
}
b.subscribers[topic] = append(b.subscribers[topic], subscriber)
return subscriber
}
func (b *Broker) Unsubscribe(topic string, subscriber *Subscriber) {
b.mutex.Lock()
defer b.mutex.Unlock()
if subscribers, found := b.subscribers[topic]; found {
for i, sub := range subscribers {
if sub == subscriber {
close(sub.Channel)
b.subscribers[topic] = append(subscribers[:i], subscribers[i+1:]...)
return
}
}
}
}
func (b *Broker) Publish(topic string, payload interface{}) {
b.mutex.Lock()
defer b.mutex.Unlock()
if subscribers, found := b.subscribers[topic]; found {
for _, sub := range subscribers {
select {
case sub.Channel <- payload:
case <-time.After(time.Second):
fmt.Printf("Subscriber slow, Unsubscribing from topic: %s\n", topic)
b.Unsubscribe(topic, sub)
}
}
}
}
func main() {
broker := NewBroker()
subscriber := broker.Subscribe("example_topic")
go func() {
for {
select {
case msg, ok := <-subscriber.Channel:
if !ok {
fmt.Println("Subscriber channel closed")
return
}
fmt.Printf("Received: %v\n", msg)
case <-subscriber.Unsubscribe:
fmt.Println("Unsubscribed")
return
}
}
}()
broker.Publish("example_topic", "Hello, World!")
broker.Publish("example_topic", "This is a test message")
time.Sleep(2 * time.Second)
broker.Unsubscribe("example_topic", subscriber)
broker.Publish("example_topic", "This message won't be received")
time.Sleep(time.Second)
}