diff --git a/controllers/search/search.go b/controllers/search/search.go index 9df3e5b..471c8d5 100644 --- a/controllers/search/search.go +++ b/controllers/search/search.go @@ -7,7 +7,6 @@ import ( "toutoukan/model/article" ) -// 全局索引变量,避免重复创建 var GlobalIndex bleve.Index func DataSearch(c *gin.Context) { @@ -78,7 +77,7 @@ func DataSearch(c *gin.Context) { } c.JSON(200, gin.H{ - "total": len(results), // 返回实际有效结果数 + "total": len(results), "took": searchResult.Took, "result": results, }) diff --git a/goroutine/consumer.go b/goroutine/consumer.go new file mode 100644 index 0000000..5c3f8e9 --- /dev/null +++ b/goroutine/consumer.go @@ -0,0 +1,27 @@ +package goroutine + +import ( + "fmt" + "sync" + "toutoukan/model/routine" +) + +func NewConsumer(ch chan routine.Task, wg *sync.WaitGroup, done chan struct{}, num int, data *routine.Data, rwmutex *sync.RWMutex) { + defer wg.Done() + for { + select { + case <-ch: + rwmutex.RLock() + fmt.Printf("消费者%d号处理消息,统计消息总数为:%d\n", num+1, data.Count) + fmt.Printf("消费者%d号:当前记录详情如下:\n", num+1) + for key, value := range data.Record { + fmt.Printf(" 键:%d,值:%d\n", key, value) + } + rwmutex.RUnlock() + case <-done: + fmt.Printf("消费者%d号退出接收\n", num+1) + return + } + } + +} diff --git a/goroutine/producer.go b/goroutine/producer.go new file mode 100644 index 0000000..d67bc7f --- /dev/null +++ b/goroutine/producer.go @@ -0,0 +1,44 @@ +package goroutine + +import ( + "fmt" + "math/rand" + "strconv" + "sync" + "time" + "toutoukan/model/routine" +) + +func NewProducer(ch chan routine.Task, wg *sync.WaitGroup, done chan struct{}, num int, mutex *sync.Mutex, data *routine.Data, rwmutex *sync.RWMutex) { + defer wg.Done() + timech := time.Tick(1 * time.Second) + rand.Seed(time.Now().UnixNano()) + for { + select { + case <-timech: + fmt.Printf("生产者%d号上锁\n", num+1) + randnum := rand.Intn(100) + task := routine.Task{ + Id: strconv.Itoa(randnum), + Content: "访问数据库", + } + mutex.Lock() + data.Count += 1 + mutex.Unlock() + + rwmutex.Lock() + data.Record[randnum] += 1 + rwmutex.Unlock() + + fmt.Printf("生产者%d号注入编号为%s,内容为:%s\n", num+1, task.Id, task.Content) + ch <- task + fmt.Printf("生产者%d号释放锁\n", num+1) + + case <-done: + fmt.Printf("生产者%d号退出任务\n", num+1) + return + } + + } + +} diff --git a/model/routine/model.go b/model/routine/model.go new file mode 100644 index 0000000..f961f18 --- /dev/null +++ b/model/routine/model.go @@ -0,0 +1,11 @@ +package routine + +type Task struct { + Id string + Content string +} + +type Data struct { + Count int + Record map[int]int +}