mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-24 05:26:02 +03:00
Update publish_subscribe.md
This commit is contained in:
parent
1355b53162
commit
ac690e1793
@ -12,63 +12,59 @@ To accomplish this, an intermediary, called a "message broker" or "event bus",
|
|||||||
receives published messages, and then routes them on to subscribers.
|
receives published messages, and then routes them on to subscribers.
|
||||||
|
|
||||||
|
|
||||||
There are three components **messages**, **topics**, **users**.
|
There are three components **messages**, **topics**, **subscriptions**.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Message struct {
|
type Message struct {
|
||||||
// Contents
|
// Contents
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
type Subscription struct {
|
type Subscription struct {
|
||||||
ch chan<- Message
|
closed bool
|
||||||
|
inbox chan Message
|
||||||
Inbox chan Message
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscription) Publish(msg Message) error {
|
func (s *Subscription) Next() (Message, error) {
|
||||||
if _, ok := <-s.ch; !ok {
|
if s.closed {
|
||||||
return errors.New("Topic has been closed")
|
return Message{}, errors.New("subscription closed")
|
||||||
}
|
}
|
||||||
|
|
||||||
s.ch <- msg
|
m, ok := <-s.inbox
|
||||||
|
if !ok {
|
||||||
|
return Message{}, errors.New("subscription closed")
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscription) Unsubscribe(Subscription) error {
|
||||||
|
s.closed = true
|
||||||
|
close(s.inbox)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Topic struct {
|
type Topic struct {
|
||||||
Subscribers []Session
|
Subscribers []Subscription
|
||||||
MessageHistory []Message
|
MessageHistory []Message
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Topic) Subscribe(uid uint64) (Subscription, error) {
|
func (t *Topic) Subscribe() (Subscription) {
|
||||||
// Get session and create one if it's the first
|
return Subscription{inbox: make(chan Message)}
|
||||||
|
|
||||||
// Add session to the Topic & MessageHistory
|
|
||||||
|
|
||||||
// Create a subscription
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Topic) Unsubscribe(Subscription) error {
|
func (t *Topic) Publish(msg Message) error {
|
||||||
// Implementation
|
for _, sub := range t.Subscribers {
|
||||||
|
if sub.closed {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Topic) Delete() error {
|
go func() {
|
||||||
// Implementation
|
sub.inbox <- msg
|
||||||
}
|
}()
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
type User struct {
|
|
||||||
ID uint64
|
|
||||||
Name string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Session struct {
|
return nil
|
||||||
User User
|
|
||||||
Timestamp time.Time
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user