当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
2 Star 0 Fork 1

JUMEI_ARCH/go-plugins
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
subscriber.go 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
Asim Aslam 提交于 2017-07-13 16:32 . A sidecar broker
package sidecar
import (
"encoding/json"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/micro/go-log"
"github.com/micro/go-micro/broker"
)
const (
pingTime = (readDeadline * 9) / 10
readLimit = 16384
readDeadline = 60 * time.Second
writeDeadline = 10 * time.Second
)
type subscriber struct {
opts broker.SubscribeOptions
conn *websocket.Conn
handler broker.Handler
topic string
exit chan bool
}
func newSubscriber(url, topic string, h broker.Handler, opts broker.SubscribeOptions) (broker.Subscriber, error) {
conn, _, err := websocket.DefaultDialer.Dial(url, make(http.Header))
if err != nil {
return nil, err
}
s := &subscriber{
opts: opts,
conn: conn,
handler: h,
topic: topic,
exit: make(chan bool),
}
go s.run()
go s.ping()
return s, nil
}
func (s *subscriber) ping() {
ticker := time.NewTicker(pingTime)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.conn.SetWriteDeadline(time.Now().Add(writeDeadline))
err := s.conn.WriteMessage(websocket.PingMessage, []byte{})
if err != nil {
log.Logf("subscriber error writing ping message: %v", err)
return
}
case <-s.exit:
return
}
}
}
func (s *subscriber) run() {
// set read limit/deadline
s.conn.SetReadLimit(readLimit)
s.conn.SetReadDeadline(time.Now().Add(readDeadline))
// set close handler
ch := s.conn.CloseHandler()
s.conn.SetCloseHandler(func(code int, text string) error {
err := ch(code, text)
s.Unsubscribe()
return err
})
// set pong handler
s.conn.SetPongHandler(func(string) error {
s.conn.SetReadDeadline(time.Now().Add(readDeadline))
return nil
})
// read and execution loop
for {
_, message, err := s.conn.ReadMessage()
if err != nil {
return
}
var msg *broker.Message
if err := json.Unmarshal(message, &msg); err != nil {
// do what?
log.Logf("subscriber error unmarshaling message: %v", err)
continue
}
if err := s.handler(&publication{
topic: s.topic,
message: msg,
}); err != nil {
log.Logf("handler execution error: %v", err)
}
}
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
func (s *subscriber) Topic() string {
return s.topic
}
func (s *subscriber) Unsubscribe() error {
select {
case <-s.exit:
return nil
default:
close(s.exit)
return s.conn.Close()
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/JMArch/go-plugins.git
git@gitee.com:JMArch/go-plugins.git
JMArch
go-plugins
go-plugins
v0.7.0

搜索帮助

0d507c66 1850385 C8b1a773 1850385