You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@answer.apache.org by li...@apache.org on 2024/09/03 02:47:12 UTC

(incubator-answer-plugins) 02/02: fix: add lock

This is an automated email from the ASF dual-hosted git repository.

linkinstar pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-answer-plugins.git

commit f909aab864256f2a115f4ac2b5d5d1440bbcbe61
Author: sy-records <52...@qq52o.cn>
AuthorDate: Mon Sep 2 16:57:51 2024 +0800

    fix: add lock
---
 search-elasticsearch/es.go   |  4 ++++
 search-elasticsearch/sync.go | 14 ++++++++++++++
 2 files changed, 18 insertions(+)

diff --git a/search-elasticsearch/es.go b/search-elasticsearch/es.go
index d04c732..ea2d0b3 100644
--- a/search-elasticsearch/es.go
+++ b/search-elasticsearch/es.go
@@ -26,6 +26,7 @@ import (
 	"fmt"
 	"github.com/apache/incubator-answer-plugins/util"
 	"strings"
+	"sync"
 
 	"github.com/apache/incubator-answer-plugins/search-elasticsearch/i18n"
 	"github.com/apache/incubator-answer/plugin"
@@ -40,6 +41,8 @@ type SearchEngine struct {
 	Config   *SearchEngineConfig
 	Operator *Operator
 	syncer   plugin.SearchSyncer
+	syncing  bool
+	lock     sync.Mutex
 }
 
 type SearchEngineConfig struct {
@@ -51,6 +54,7 @@ type SearchEngineConfig struct {
 func init() {
 	plugin.Register(&SearchEngine{
 		Config: &SearchEngineConfig{},
+		lock:   sync.Mutex{},
 	})
 }
 
diff --git a/search-elasticsearch/sync.go b/search-elasticsearch/sync.go
index 76a137f..13b6e33 100644
--- a/search-elasticsearch/sync.go
+++ b/search-elasticsearch/sync.go
@@ -27,7 +27,20 @@ import (
 
 func (s *SearchEngine) sync() {
 	var page, pageSize = 1, 100
+	if s.syncing {
+		log.Warnf("es: syncing is running, skip")
+		return
+	}
+
 	go func() {
+		s.lock.Lock()
+		defer s.lock.Unlock()
+		if s.syncing {
+			log.Warnf("es: syncing is running, skip")
+			return
+		}
+
+		s.syncing = true
 		log.Info("es: start sync questions...")
 		page = 1
 		for {
@@ -68,6 +81,7 @@ func (s *SearchEngine) sync() {
 
 			page += 1
 		}
+		s.syncing = false
 		log.Info("es: sync done")
 	}()
 }