|
| 1 | +Publish & Subscribe Messaging Pattern |
| 2 | +============ |
| 3 | +Publish-Subscribe is a messaging pattern used to communicate messages between |
| 4 | +different components without these components knowing anything about each other's identity. |
| 5 | + |
| 6 | +It is similar to the Observer behavioral design pattern. |
| 7 | +The fundamental design principals of both Observer and Publish-Subscribe is the decoupling of |
| 8 | +those interested in being informed about `Event Messages` from the informer (Observers or Publishers). |
| 9 | +Meaning that you don't have to program the messages to be sent directly to specific receivers. |
| 10 | + |
| 11 | +To accomplish this, an intermediary, called a "message broker" or "event bus", |
| 12 | +receives published messages, and then routes them on to subscribers. |
| 13 | + |
| 14 | + |
| 15 | +There are three components **messages**, **topics**, **users**. |
| 16 | + |
| 17 | +```go |
| 18 | +type Message struct { |
| 19 | + // Contents |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +type Subscription struct { |
| 24 | + ch chan<- Message |
| 25 | + |
| 26 | + Inbox chan Message |
| 27 | +} |
| 28 | + |
| 29 | +func (s *Subscription) Publish(msg Message) error { |
| 30 | + if _, ok := ch; !ok { |
| 31 | + return errors.New("Topic has been closed") |
| 32 | + } |
| 33 | + |
| 34 | + ch <- msg |
| 35 | + |
| 36 | + return nil |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +```go |
| 41 | +type Topic struct { |
| 42 | + Subscribers []Session |
| 43 | + MessageHistory []Message |
| 44 | +} |
| 45 | + |
| 46 | +func (t *Topic) Subscribe(uid uint64) (Subscription, error) { |
| 47 | + // Get session and create one if it's the first |
| 48 | + |
| 49 | + // Add session to the Topic & MessageHistory |
| 50 | + |
| 51 | + // Create a subscription |
| 52 | +} |
| 53 | + |
| 54 | +func (t *Topic) Unsubscribe(Subscription) error { |
| 55 | + // Implementation |
| 56 | +} |
| 57 | + |
| 58 | +func (t *Topic) Delete() error { |
| 59 | + // Implementation |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +```go |
| 64 | +type User struct { |
| 65 | + ID uint64 |
| 66 | + Name string |
| 67 | +} |
| 68 | + |
| 69 | +type Session struct { |
| 70 | + User User |
| 71 | + Timestamp time.Time |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +Improvements |
| 76 | +============ |
| 77 | +Events can be published in a parallel fashion by utilizing stackless goroutines. |
| 78 | + |
| 79 | +Performance can be improved by dealing with straggler subscribers |
| 80 | +by using a buffered inbox and you stop sending events once the inbox is full. |
0 commit comments