fix: allow subscribers to register and deregister multi times.

This commit is contained in:
武新飞 2018-12-19 18:22:27 +08:00 committed by Vasiliy Tolstov
parent 3f5cbf2bcd
commit 532edc786f

33
http.go
View File

@ -9,12 +9,12 @@ import (
"sort"
"sync"
"github.com/micro/go-log"
log "github.com/micro/go-log"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/server"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/server"
"github.com/micro/go-plugins/codec/jsonrpc"
"github.com/micro/go-plugins/codec/protorpc"
)
@ -28,6 +28,7 @@ var (
"application/octet-stream": protorpc.NewCodec,
}
)
type httpServer struct {
sync.Mutex
opts server.Options
@ -35,6 +36,8 @@ type httpServer struct {
exit chan chan error
registerOnce sync.Once
subscribers map[*httpSubscriber][]broker.Subscriber
// used for first registration
registered bool
}
func init() {
@ -162,6 +165,19 @@ func (h *httpServer) Register() error {
h.registerOnce.Do(func() {
log.Logf("Registering node: %s", opts.Name+"-"+opts.Id)
})
if err := opts.Registry.Register(service, rOpts...); err != nil {
return err
}
h.Lock()
defer h.Unlock()
if h.registered {
return nil
}
h.registered = true
for sb, _ := range h.subscribers {
handler := h.createSubHandler(sb, opts)
@ -171,14 +187,11 @@ func (h *httpServer) Register() error {
}
sub, err := opts.Broker.Subscribe(sb.Topic(), handler, subOpts...)
if err != nil {
log.Logf("Registering subscriber: %s, err: %s", sb.Topic, err)
return
return err
}
h.subscribers[sb] = []broker.Subscriber{sub}
}
})
return opts.Registry.Register(service, rOpts...)
return nil
}
func (h *httpServer) Deregister() error {
@ -194,6 +207,12 @@ func (h *httpServer) Deregister() error {
}
h.Lock()
if !h.registered {
h.Unlock()
return nil
}
h.registered = false
for sb, subs := range h.subscribers {
for _, sub := range subs {
log.Logf("Unsubscribing from topic: %s", sub.Topic())