Browse Source

修复组件BUG

lxg 3 years ago
parent
commit
fb25a01734
3 changed files with 31 additions and 8 deletions
  1. 2 0
      gateway/cli/server.go
  2. 6 0
      micro.go
  3. 23 8
      service.go

+ 2 - 0
gateway/cli/server.go

@@ -187,12 +187,14 @@ func (svr *Server) Serve(listener net.Listener) (err error) {
 		wg.Add(1)
 		go func() {
 			svr.tcpServe(listener)
+			wg.Done()
 		}()
 	}
 	if runtime.GOOS == "linux" {
 		wg.Add(1)
 		go func() {
 			svr.unixServe(path.Join(os.TempDir(), os.Getenv("MICRO_SERVICE_NAME")+".sock"))
+			wg.Done()
 		}()
 	}
 	wg.Wait()

+ 6 - 0
micro.go

@@ -20,6 +20,12 @@ type (
 	applicationKey struct {
 	}
 
+	handleEntry struct {
+		Method  string `json:"method"`
+		Func    HandleFunc
+		Options []HandleOption
+	}
+
 	HandleTickerFunc func(ctx context.Context)
 
 	tickPtr struct {

+ 23 - 8
service.go

@@ -59,7 +59,9 @@ type Service struct {
 	triesRegister int
 	tickTimer     *time.Timer
 	tickTree      *btree.BTree
+	deferHandles  []handleEntry
 	environment   string
+	readyFlag     int32
 	exitFlag      int32
 }
 
@@ -145,6 +147,14 @@ func (svr *Service) DeferTick(duration time.Duration, callback HandleTickerFunc,
 
 //Handle 处理函数
 func (svr *Service) Handle(method string, cb HandleFunc, opts ...HandleOption) {
+	if atomic.LoadInt32(&svr.readyFlag) != 1 {
+		svr.deferHandles = append(svr.deferHandles, handleEntry{
+			Method:  method,
+			Func:    cb,
+			Options: opts,
+		})
+		return
+	}
 	//disable cli default
 	opt := &HandleOptions{HttpMethod: "POST", DisableCli: true}
 	for _, f := range opts {
@@ -505,7 +515,11 @@ func (svr *Service) Run() (err error) {
 		}
 	}
 	log.Infof("service started")
-	//waiting
+	if atomic.CompareAndSwapInt32(&svr.readyFlag, 0, 1) {
+		for _, he := range svr.deferHandles {
+			svr.Handle(he.Method, he.Func, he.Options...)
+		}
+	}
 	ch := make(chan os.Signal, 1)
 	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
 	select {
@@ -525,13 +539,14 @@ func New(opts ...Option) *Service {
 		opt(o)
 	}
 	svr := &Service{
-		opts:        o,
-		upTime:      time.Now(),
-		registry:    o.registry,
-		tickTimer:   time.NewTimer(math.MaxInt64),
-		tickTree:    btree.New(64),
-		client:      NewClient(o.registry),
-		environment: EnvironmentHost,
+		opts:         o,
+		upTime:       time.Now(),
+		registry:     o.registry,
+		deferHandles: make([]handleEntry, 0),
+		tickTimer:    time.NewTimer(math.MaxInt64),
+		tickTree:     btree.New(64),
+		client:       NewClient(o.registry),
+		environment:  EnvironmentHost,
 	}
 	svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
 	return svr