tianxiaoliang commented on a change in pull request #844:
URL: 
https://github.com/apache/servicecomb-service-center/pull/844#discussion_r570664808



##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       } else {

Review comment:
       没必要用else,再想想写法,消除掉

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       } else {
+                                               return
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)
+}
+
+func cleanInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       session, err := client.GetMongoClient().StartSession(ctx)
+       if err != nil {
+               return err
+       }
+       if err = session.StartTransaction(); err != nil {
+               return err
+       }
+       defer session.EndSession(ctx)
+
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+
+       result, err := client.GetMongoClient().FindOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to query instance: %v", err)
+               return err
+       }
+       var ins mongo.Instance
+       err = result.Decode(&ins)
+       if err != nil {
+               log.Error("decode instance failed: %v", err)
+               return err
+       }
+       ttl := ins.InstanceInfo.HealthCheck.Interval * 
(ins.InstanceInfo.HealthCheck.Times + 1)
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       if judgeRefreshTimeTimeout(ins.RefreshTime, ttl) {
+               return nil
+       }
+       err = removeDBInstance(ctx, ins.InstanceInfo.ServiceId, 
ins.InstanceInfo.InstanceId)
+       if err != nil {
+               log.Error("fail to remote instance in db: %v", err)
+               errAbort := session.AbortTransaction(ctx)
+               if errAbort != nil {
+                       return errAbort
+               }
+               return err
+       }
+       err = session.CommitTransaction(ctx)
+       return err
+}
+
+func removeDBInstance(ctx context.Context, serviceID string, instanceID 
string) error {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       res, err := client.GetMongoClient().DeleteOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to clean instance", err)
+               return err
+       }
+       log.Info(fmt.Sprintf("delete from mongodb:%+v", res))
+       return nil
+}
+
+func findInstance(ctx context.Context, serviceID string, instanceID string) 
(int32, int32, error) {

Review comment:
       函数名不直观,意义和返回值不相符

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))

Review comment:
       没必要传withstandby,因为都是新设计的配置项,不再需要支持ini格式,只需要支持yaml

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       } else {
+                                               return
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)
+}
+
+func cleanInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       session, err := client.GetMongoClient().StartSession(ctx)
+       if err != nil {
+               return err
+       }
+       if err = session.StartTransaction(); err != nil {
+               return err
+       }
+       defer session.EndSession(ctx)
+
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,

Review comment:
       常量极其内容我希望简写,从xxxinfo写为xxx,大数据量中,这样是一定可以节约内存和计算的

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))

Review comment:
       魔鬼数字

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       } else {
+                                               return
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)
+}
+
+func cleanInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       session, err := client.GetMongoClient().StartSession(ctx)
+       if err != nil {
+               return err
+       }
+       if err = session.StartTransaction(); err != nil {
+               return err
+       }
+       defer session.EndSession(ctx)
+
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+
+       result, err := client.GetMongoClient().FindOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to query instance: %v", err)
+               return err
+       }
+       var ins mongo.Instance
+       err = result.Decode(&ins)
+       if err != nil {
+               log.Error("decode instance failed: %v", err)
+               return err
+       }
+       ttl := ins.InstanceInfo.HealthCheck.Interval * 
(ins.InstanceInfo.HealthCheck.Times + 1)
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       if judgeRefreshTimeTimeout(ins.RefreshTime, ttl) {
+               return nil
+       }
+       err = removeDBInstance(ctx, ins.InstanceInfo.ServiceId, 
ins.InstanceInfo.InstanceId)
+       if err != nil {
+               log.Error("fail to remote instance in db: %v", err)
+               errAbort := session.AbortTransaction(ctx)
+               if errAbort != nil {
+                       return errAbort
+               }
+               return err
+       }
+       err = session.CommitTransaction(ctx)
+       return err
+}
+
+func removeDBInstance(ctx context.Context, serviceID string, instanceID 
string) error {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       res, err := client.GetMongoClient().DeleteOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to clean instance", err)
+               return err
+       }
+       log.Info(fmt.Sprintf("delete from mongodb:%+v", res))
+       return nil
+}
+
+func findInstance(ctx context.Context, serviceID string, instanceID string) 
(int32, int32, error) {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       result, err := client.GetMongoClient().FindOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               return 0, 0, err
+       }
+       var ins mongo.Instance
+       err = result.Decode(&ins)
+       if err != nil {
+               log.Error("decode instance failed: ", err)
+               return 0, 0, err
+       }
+       return ins.InstanceInfo.HealthCheck.Interval, 
ins.InstanceInfo.HealthCheck.Times, nil
+}
+
+func updateInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstanceInfo, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       update := bson.M{
+               "$set": bson.M{mongo.ColumnRefreshTime: time.Now()},
+       }
+       result, err := client.GetMongoClient().FindOneAndUpdate(ctx, 
mongo.CollectionInstance, filter, update)
+       if err != nil {
+               log.Error("failed to update refresh time of instance: ", err)
+               return err
+       }
+       return result.Err()
+}
+
+func judgeRefreshTimeTimeout(refreshTime time.Time, ttl int32) bool {

Review comment:
       方法名不直观

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("heartbeat.cache.capacity", 10000, 
config.WithStandby("heartbeat_cache_capacity"))
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("heartbeat.worker.num", 10, 
config.WithStandby("heartbeat_worker_num"))
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)

Review comment:
       time.Duration(heartbeatInfo.ttl)*time.Second)  我无法一眼看出这是多少秒,代码不够直观

##########
File path: etc/conf/app.conf
##########
@@ -70,8 +70,15 @@ registry_plugin = etcd
 # manager_cluster = "127.0.0.1:2379"
 manager_cluster = "127.0.0.1:2379"
 
-# heartbeat_plugin="heartbeatchecker"
-heartbeat_plugin="heartbeatchecker"
+# Mongo's heartbeat plugin
+# heartbeat_plugin="heartbeatchecker or heartbeatcache"
+# if heartbeat_plugin equals to 'heartbeatcache', should set 
heartbeat_cache_capacity and heartbeat_worker_num
+# heartbeat_cache_capacity = 10000
+# heartbeat_worker_num = 10

Review comment:
       不要ini设计

##########
File path: datasource/mongo/mongo.go
##########
@@ -79,7 +79,7 @@ func (ds *DataSource) initialize() error {
 }
 
 func (ds *DataSource) initPlugins() error {
-       kind := config.GetString("registry.heartbeat.kind", "heartbeatchecker", 
config.WithStandby("heartbeat_plugin"))
+       kind := config.GetString("registry.mongo.heartbeat.kind", 
"heartbeatcache", config.WithStandby("heartbeat_plugin"))

Review comment:
       不要WithStandby 

##########
File path: datasource/mongo/bootstrap/bootstrap.go
##########
@@ -21,6 +21,7 @@ import (
        _ "github.com/apache/servicecomb-service-center/datasource/mongo"
 
        // heartbeat
+       _ 
"github.com/apache/servicecomb-service-center/datasource/mongo/heartbeat/heartbeatcache"

Review comment:
       heartbeat/heartbeatcache ->heartbeat/cache
   
   checker同理

##########
File path: datasource/mongo/mongo.go
##########
@@ -79,7 +79,7 @@ func (ds *DataSource) initialize() error {
 }
 
 func (ds *DataSource) initPlugins() error {
-       kind := config.GetString("registry.heartbeat.kind", "heartbeatchecker", 
config.WithStandby("heartbeat_plugin"))
+       kind := config.GetString("registry.mongo.heartbeat.kind", 
"heartbeatcache")

Review comment:
       heartbeatcache 改为cache

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeatcache.go
##########
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "errors"
+       "fmt"
+
+       pb "github.com/go-chassis/cari/discovery"
+
+       
"github.com/apache/servicecomb-service-center/datasource/mongo/heartbeat"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/pkg/util"
+)
+
+func init() {
+       heartbeat.Install("heartbeatcache", NewHeartBeatCheck)

Review comment:
       插件名cache

##########
File path: etc/conf/app.yaml
##########
@@ -83,6 +83,15 @@ registry:
     request:
       timeout:
   mongo:
+    heartbeat:
+      # Mongo's heartbeat plugin
+      # heartbeat.kind="heartbeatchecker or heartbeatcache"
+      # if heartbeat.kind equals to 'heartbeatcache', should set cacheCapacity 
and workerNum
+      # capacity = 10000
+      # workerNum = 10
+      kind: heartbeatcache

Review comment:
       heartbeatcache 改成cache

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeatcache.go
##########
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "errors"
+       "fmt"
+
+       pb "github.com/go-chassis/cari/discovery"
+
+       
"github.com/apache/servicecomb-service-center/datasource/mongo/heartbeat"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/pkg/util"
+)
+
+func init() {
+       heartbeat.Install("heartbeatcache", NewHeartBeatCheck)
+}
+
+type HeartBeatCheck struct {
+}
+
+func NewHeartBeatCheck(opts heartbeat.Options) (heartbeat.HealthCheck, error) {
+       return &HeartBeatCheck{}, nil
+}
+
+func (h *HeartBeatCheck) Heartbeat(ctx context.Context, request 
*pb.HeartbeatRequest) (*pb.HeartbeatResponse, error) {
+       log.Info("cache: " + fmt.Sprintf("%s\n", request.InstanceId))

Review comment:
       这个接口会由于fmt+io而非常慢,删掉,debug日志都不要打

##########
File path: datasource/mongo/heartbeat/heartbeatcache/heartbeatcache.go
##########
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "errors"
+       "fmt"
+
+       pb "github.com/go-chassis/cari/discovery"
+
+       
"github.com/apache/servicecomb-service-center/datasource/mongo/heartbeat"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/pkg/util"
+)
+
+func init() {
+       heartbeat.Install("heartbeatcache", NewHeartBeatCheck)
+}
+
+type HeartBeatCheck struct {
+}
+
+func NewHeartBeatCheck(opts heartbeat.Options) (heartbeat.HealthCheck, error) {
+       return &HeartBeatCheck{}, nil
+}
+
+func (h *HeartBeatCheck) Heartbeat(ctx context.Context, request 
*pb.HeartbeatRequest) (*pb.HeartbeatResponse, error) {
+       log.Info("cache: " + fmt.Sprintf("%s\n", request.InstanceId))
+       if ins, ok := instanceHeartbeatStore.Get(request.InstanceId); ok {
+               return inCacheStrategy(ctx, request, ins)
+       } else {
+               return notInCacheStrategy(ctx, request)
+       }
+}
+
+func inCacheStrategy(ctx context.Context, request *pb.HeartbeatRequest, 
insHeartbeatInfo interface{}) (*pb.HeartbeatResponse, error) {
+       remoteIP := util.GetIPFromContext(ctx)
+       heartbeatInfo, ok := insHeartbeatInfo.(*instanceHeartbeatInfo)
+       if !ok {
+               err := errors.New("instanceHeartbeatInfo type conversion 
failed. ")

Review comment:
       搞成错误变量

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {

Review comment:
       addHeartbeatTask更易懂

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)
+}
+
+func cleanInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       session, err := client.GetMongoClient().StartSession(ctx)

Review comment:
       掉这个接口意味着什么?是否成本比较高,如果是直接从现有的连接池里拿一个conn再执行就对了

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance

Review comment:
       这里如果不加超时保护,就会导致大量心跳积压,占用链接

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)
+}
+
+func cleanInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       session, err := client.GetMongoClient().StartSession(ctx)
+       if err != nil {
+               return err
+       }
+       if err = session.StartTransaction(); err != nil {
+               return err
+       }
+       defer session.EndSession(ctx)
+
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnInstanceID}): instanceID,
+       }
+
+       result, err := client.GetMongoClient().FindOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to query instance: %v", err)
+               return err
+       }
+       var ins mongo.Instance
+       err = result.Decode(&ins)
+       if err != nil {
+               log.Error("decode instance failed: %v", err)
+               return err
+       }
+       ttl := ins.Instance.HealthCheck.Interval * 
(ins.Instance.HealthCheck.Times + 1)
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       if timeout(ins.RefreshTime, ttl) {
+               return nil
+       }
+       err = removeDBInstance(ctx, ins.Instance.ServiceId, 
ins.Instance.InstanceId)
+       if err != nil {
+               log.Error("fail to remote instance in db: %v", err)
+               errAbort := session.AbortTransaction(ctx)
+               if errAbort != nil {
+                       return errAbort
+               }
+               return err
+       }
+       err = session.CommitTransaction(ctx)
+       return err
+}
+
+func removeDBInstance(ctx context.Context, serviceID string, instanceID 
string) error {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       res, err := client.GetMongoClient().DeleteOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               log.Error("failed to clean instance", err)
+               return err
+       }
+       log.Info(fmt.Sprintf("delete from mongodb:%+v", res))
+       return nil
+}
+
+func findInstance(ctx context.Context, serviceID string, instanceID string) 
(*mongo.Instance, error) {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       result, err := client.GetMongoClient().FindOne(ctx, 
mongo.CollectionInstance, filter)
+       if err != nil {
+               return nil, err
+       }
+       var ins mongo.Instance
+       err = result.Decode(&ins)
+       if err != nil {
+               log.Error("decode instance failed: ", err)
+               return nil, err
+       }
+       return &ins, nil
+}
+
+func updateInstance(ctx context.Context, serviceID string, instanceID string) 
error {
+       filter := bson.M{
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnServiceID}):  serviceID,
+               mongo.StringBuilder([]string{mongo.ColumnInstance, 
mongo.ColumnInstanceID}): instanceID,
+       }
+       update := bson.M{
+               "$set": bson.M{mongo.ColumnRefreshTime: time.Now()},
+       }
+       result, err := client.GetMongoClient().FindOneAndUpdate(ctx, 
mongo.CollectionInstance, filter, update)
+       if err != nil {
+               log.Error("failed to update refresh time of instance: ", err)
+               return err
+       }
+       return result.Err()
+}
+
+func timeout(refreshTime time.Time, ttl int32) bool {

Review comment:
       isOutdate

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance

Review comment:
       这里如果不加超时保护,就会导致大量心跳积压,hang住客户端导致服务端被占用链接

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance

Review comment:
       这里如果不加超时保护,就会导致大量心跳积压,hang住客户端导致服务端被占用tcp链接

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance

Review comment:
       这里如果不加超时保护,就会导致大量心跳积压,hang住客户端导致服务端被占用tcp链接,其他的业务就无法正常进行

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance

Review comment:
       
这里如果不加超时保护,就会导致大量心跳积压,hang住客户端导致服务端被占用tcp链接,其他的业务就无法正常进行,这里超时后要返回错误,并最终反回给客户端,too
 much concurrency

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return

Review comment:
       这里worker会退出,这是个严重的问题,要打warn日志跟踪

##########
File path: datasource/mongo/heartbeat/cache/heartbeat.go
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except request compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to request writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package heartbeatcache
+
+import (
+       "context"
+       "fmt"
+       "runtime"
+       "time"
+
+       "github.com/patrickmn/go-cache"
+       "go.mongodb.org/mongo-driver/bson"
+
+       "github.com/apache/servicecomb-service-center/datasource/mongo"
+       "github.com/apache/servicecomb-service-center/datasource/mongo/client"
+       "github.com/apache/servicecomb-service-center/pkg/gopool"
+       "github.com/apache/servicecomb-service-center/pkg/log"
+       "github.com/apache/servicecomb-service-center/server/config"
+)
+
+const (
+       defaultTTL              = 30
+       defaultCacheCapacity    = 10000
+       defaultWorkNum          = 10
+       instanceCheckerInternal = 1 * time.Second
+       ctxTimeout              = 5 * time.Second
+)
+
+// Store cache structure
+type instanceHeartbeatInfo struct {
+       serviceID   string
+       instanceID  string
+       ttl         int32
+       lastRefresh time.Time
+}
+
+var (
+       cacheChan              chan *instanceHeartbeatInfo
+       instanceHeartbeatStore = cache.New(0, instanceCheckerInternal)
+       workerNum              = runtime.NumCPU()
+)
+
+func init() {
+       capacity := config.GetInt("registry.mongo.heartbeat.cacheCapacity", 
defaultCacheCapacity)
+       cacheChan = make(chan *instanceHeartbeatInfo, capacity)
+       num := config.GetInt("registry.mongo.heartbeat.workerNum", 
defaultWorkNum)
+       if num != 0 {
+               workerNum = num
+       }
+       instanceHeartbeatStore.OnEvicted(func(k string, v interface{}) {
+               instanceInfo, ok := v.(*instanceHeartbeatInfo)
+               if ok && instanceInfo != nil {
+                       ctx, cancel := 
context.WithTimeout(context.Background(), ctxTimeout)
+                       defer cancel()
+                       err := cleanInstance(ctx, instanceInfo.serviceID, 
instanceInfo.instanceID)
+                       if err != nil {
+                               log.Error("failed to cleanInstance in 
mongodb.", err)
+                       }
+               }
+       })
+
+       for i := 1; i <= workerNum; i++ {
+               gopool.Go(func(ctx context.Context) {
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case heartbeatInfo, ok := <-cacheChan:
+                                       if ok {
+                                               
instanceHeartbeatStore.Set(heartbeatInfo.instanceID, heartbeatInfo, 
time.Duration(heartbeatInfo.ttl)*time.Second)
+                                       }
+                               }
+                       }
+               })
+       }
+}
+
+func addCacheInstance(serviceID string, instanceID string, ttl int32) {
+       // Unassigned setting default value is 30s
+       if ttl <= 0 {
+               ttl = defaultTTL
+       }
+       newInstance := &instanceHeartbeatInfo{
+               serviceID:   serviceID,
+               instanceID:  instanceID,
+               ttl:         ttl,
+               lastRefresh: time.Now(),
+       }
+       cacheChan <- newInstance
+}
+
+func removeCacheInstance(instanceID string) {
+       instanceHeartbeatStore.Delete(instanceID)

Review comment:
       这层封装有点没必要了,而且只有ut在调用,那不如大写对外开放




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to