Skip to content

Commit

Permalink
fix bug: close conn
Browse files Browse the repository at this point in the history
  • Loading branch information
wangchuxiao-dev committed Jul 31, 2023
1 parent 2cac809 commit 5a9a890
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 6 additions & 3 deletions discoveryregistry/zookeeper/discover.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ var (
ErrConnIsNilButLocalNotNil = errors.New("conn is nil, but local is not nil")
)

func (s *ZkClient) watch() {
for {
event := <-s.eventChan
func (s *ZkClient) watch(ctx context.Context) {
select {
case <-ctx.Done():
log.ZDebug(context.Background(), "zk watch ctx done")
return
case event := <-s.eventChan:
log.ZDebug(context.Background(), "zk recv event", "event", event)
switch event.Type {
case zk.EventSession:
Expand Down
8 changes: 7 additions & 1 deletion discoveryregistry/zookeeper/zk.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package zookeeper

import (
"context"
"net"
"strconv"
"sync"
Expand Down Expand Up @@ -56,6 +57,7 @@ type ZkClient struct {

resolvers map[string]*Resolver
localConns map[string][]grpc.ClientConnInterface
cancel context.CancelFunc

balancerName string

Expand Down Expand Up @@ -111,6 +113,8 @@ func NewClient(zkServers []string, zkRoot string, options ...ZkOption) (*ZkClien
resolvers: make(map[string]*Resolver),
lock: &sync.Mutex{},
}
baseCtx, cancel := context.WithCancel(context.Background())
client.cancel = cancel
client.ticker = time.NewTicker(defaultFreq)
for _, option := range options {
option(client)
Expand Down Expand Up @@ -138,12 +142,14 @@ func NewClient(zkServers []string, zkRoot string, options ...ZkOption) (*ZkClien
}
resolver.Register(client)
go client.refresh()
go client.watch()
go client.watch(baseCtx)
time.Sleep(time.Millisecond * 50)
return client, nil
}

func (s *ZkClient) CloseZK() {
s.cancel()
s.ticker.Stop()
s.conn.Close()
}

Expand Down

0 comments on commit 5a9a890

Please sign in to comment.