好用ChanBroker,轻松实现的goroutine pub-sub模型

myself659 · · 667 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

[ChanBroker](https://github.com/myself659/ChanBroker) https://github.com/myself659/ChanBroker ### Introduction ChanBroker, a Broker for goroutine, is simliar to kafka In ChanBroker has three types of goroutine: - Producer - Consumer(Subscriber) - Broker ### Usage code: ``` package main import ( "fmt" "github.com/myself659/ChanBroker" "time" ) type event struct { id int info string } func SubscriberDo(sub ChanBroker.Subscriber, b *ChanBroker.ChanBroker, id int) { for { select { case c := <-sub: switch t := c.(type) { case event: fmt.Println("SubscriberId:", id, " event:", t) default: } } } } func PublisherDo(b *ChanBroker.ChanBroker) { ticker := time.NewTicker(time.Second) i := 0 for range ticker.C { ev := event{i, "event"} b.PubContent(ev) fmt.Println("Publisher:", ev) i++ if 3 == i { break } } ticker.Stop() b.StopBroker() } func main() { // launch broker goroutine b := ChanBroker.NewChanBroker(time.Second) // register Subscriber and launch Subscriber goroutine sub1, _ := b.RegSubscriber(1) go SubscriberDo(sub1, b, 1) sub2, _ := b.RegSubscriber(1) go SubscriberDo(sub2, b, 2) // launch Publisher goroutine go PublisherDo(b) // after 3.5s, exit process <-time.After(3500 * time.Millisecond) fmt.Println("exit") } ``` output: ``` Publisher: {0 event} SubscriberId: 1 event: {0 event} SubscriberId: 2 event: {0 event} Publisher: {1 event} SubscriberId: 2 event: {1 event} SubscriberId: 1 event: {1 event} Publisher: {2 event} SubscriberId: 2 event: {2 event} SubscriberId: 1 event: {2 event} exit ```

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

667 次点击  
加入收藏 微博
2 回复  |  直到 2018-12-12 22:25:03
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传