From e2a950fdbea28e0951dbdc90551d4cc52bb13534 Mon Sep 17 00:00:00 2001 From: Edward Date: Tue, 28 Apr 2020 12:31:29 +0800 Subject: [PATCH] add a messaging pattern --- gomore/messaging/README.md | 7 +++ gomore/messaging/messaging.go | 70 ++++++++++++++++++++++++++++++ gomore/messaging/messaging_test.go | 1 + 3 files changed, 78 insertions(+) create mode 100644 gomore/messaging/README.md create mode 100644 gomore/messaging/messaging.go create mode 100644 gomore/messaging/messaging_test.go diff --git a/gomore/messaging/README.md b/gomore/messaging/README.md new file mode 100644 index 0000000..31fa4c7 --- /dev/null +++ b/gomore/messaging/README.md @@ -0,0 +1,7 @@ +# 发布订阅模式 + +发布-订阅是一种消息传递模式,基本设计原则是将消息发布者和提供者分开,常常用于在不同组件之间传递消息。 + +它有点类似于观察者行为设计模式,但是发布订阅模式往往要依赖一个中介<通常是各类的消息中间件,消息队列> + +有三个关键组是:消息本身、消息主题、订阅用户。 diff --git a/gomore/messaging/messaging.go b/gomore/messaging/messaging.go new file mode 100644 index 0000000..d6ef4c8 --- /dev/null +++ b/gomore/messaging/messaging.go @@ -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 +} diff --git a/gomore/messaging/messaging_test.go b/gomore/messaging/messaging_test.go new file mode 100644 index 0000000..771d873 --- /dev/null +++ b/gomore/messaging/messaging_test.go @@ -0,0 +1 @@ +package gomore