mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-25 13:16:02 +03:00
add a messaging pattern
This commit is contained in:
parent
60927fbd3a
commit
e2a950fdbe
7
gomore/messaging/README.md
Normal file
7
gomore/messaging/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 发布订阅模式
|
||||
|
||||
发布-订阅是一种消息传递模式,基本设计原则是将消息发布者和提供者分开,常常用于在不同组件之间传递消息。
|
||||
|
||||
它有点类似于观察者行为设计模式,但是发布订阅模式往往要依赖一个中介<通常是各类的消息中间件,消息队列>
|
||||
|
||||
有三个关键组是:消息本身、消息主题、订阅用户。
|
70
gomore/messaging/messaging.go
Normal file
70
gomore/messaging/messaging.go
Normal 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
|
||||
}
|
1
gomore/messaging/messaging_test.go
Normal file
1
gomore/messaging/messaging_test.go
Normal file
@ -0,0 +1 @@
|
||||
package gomore
|
Loading…
Reference in New Issue
Block a user