add a messaging pattern

This commit is contained in:
Edward 2020-04-28 12:31:29 +08:00
parent 60927fbd3a
commit e2a950fdbe
3 changed files with 78 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# 发布订阅模式
发布-订阅是一种消息传递模式,基本设计原则是将消息发布者和提供者分开,常常用于在不同组件之间传递消息。
它有点类似于观察者行为设计模式,但是发布订阅模式往往要依赖一个中介<通常是各类的消息中间件消息队列>
有三个关键组是:消息本身、消息主题、订阅用户。

View File

@ -0,0 +1,70 @@
package gomore
import (
"errors"
"time"
)
//Message for msg in bus
type Message struct {
Alarm int
priority int
}
//User for user
type User struct {
ID uint64
Name string
}
//Session of user
type Session struct {
User User
Timestamp time.Time
}
//Subscription for user
type Subscription struct {
ch chan Message
Inbox chan Message
}
//Publish a message to subscription queue
func (s *Subscription) Publish(msg Message) error {
if _, ok := <-s.ch; !ok {
return errors.New("Topic has been closed")
}
s.ch <- msg
return nil
}
//Topic that user is interested in
type Topic struct {
Subscribers []Session
MessageHistory []Message
}
//Subscribe a topic
func (t *Topic) Subscribe(uid uint64) (Subscription, error) {
// Get session and create one if it's the first
// Add session to the Topic & MessageHistory
// Create a subscription
return Subscription{}, nil
}
//Unsubscribe remove Subscription
func (t *Topic) Unsubscribe(Subscription) error {
return nil
}
//Delete message
func (t *Topic) Delete() error {
return nil
}

View File

@ -0,0 +1 @@
package gomore