package service import ( "fmt" "github.com/gin-gonic/gin" "github.com/go-xorm/xorm" "github.com/gogf/gf/util/gconv" "go_sku_server/model" "go_sku_server/pkg/mysql" "sync" "time" ) type SampleService struct { } //获取分类列表 func (ss *SampleService) GetSampleList(ctx *gin.Context) (data map[string]interface{}, err error) { id := gconv.Int(ctx.Request.FormValue("id")) goodsId := gconv.Int(ctx.Request.FormValue("goods_id")) classId := gconv.Int(ctx.Request.FormValue("class_id")) page := gconv.Int(ctx.Request.FormValue("page")) limit := gconv.Int(ctx.Request.FormValue("limit")) if limit == 0 { limit = 10 } var start int if page == 0 || page == 1 { page = 1 start = 0 } else { start = (page - 1) * limit } query := mysql.Conn("liexin_data").Table("lie_sample").Where("status = ?", 1) if id != 0 { query.Where("id = ?", id) } if goodsId != 0 { query.Where("goods_id = ?", goodsId) } if classId != 0 { query.Where("class_id = ?", classId) } var sampleList []model.Sample query.OrderBy("update_time DESC").Limit(limit, start) err = query.Find(&sampleList) if err != nil && err != xorm.ErrNotExist { return nil, err } //构建和之前接口的数据一样的格式,有点操蛋 data = make(map[string]interface{}) goodsMap := make(map[string]interface{}) var goodsIdsSlice []string sampleGoodsMap := make(map[string]model.Sample) for _, sample := range sampleList { goodsIdStr := gconv.String(sample.GoodsId) goodsIdsSlice = append(goodsIdsSlice, goodsIdStr) } goodsMap = ss.GetGoods(ctx, goodsIdsSlice) for _, sample := range sampleList { classService := SampleClassService{} class, _ := classService.GetSampleClass(sample.ClassId) sample.ClassName = class.ClassName sample.GoodsInfo = goodsMap[gconv.String(sample.GoodsId)] sampleGoodsMap[gconv.String(sample.GoodsId)] = sample } data["data"] = sampleGoodsMap return data, err } func (ss *SampleService) GetGoods(ctx *gin.Context, goodsIds []string) map[string]interface{} { //抽取自营 或者联营 goods_id zyService := ZiyingService{} //实例化自营查询 lyService := LyService{} //实例化自营查询 ch := make(chan sync.Map) //管道 p := 0 //总共协程 zyGoodsId := make([]string, 0) lyGoodsId := make([]string, 0) for _, goodsId := range goodsIds { if goodsId == "" { continue } if len(goodsId) < 19 { //自营 zyGoodsId = append(zyGoodsId, goodsId) if len(zyGoodsId) >= 10 { go zyService.ZyGoodsDetail(ctx, zyGoodsId, ch) zyGoodsId = zyGoodsId[:0:0] p++ } } else { //联营 lyGoodsId = append(lyGoodsId, goodsId) if len(lyGoodsId) >= 10 { go lyService.LyGoodsDetail(ctx, lyGoodsId, ch) lyGoodsId = lyGoodsId[:0:0] p++ } } } if len(zyGoodsId) > 0 { go zyService.ZyGoodsDetail(ctx, zyGoodsId, ch) p++ } if len(lyGoodsId) > 0 { go lyService.LyGoodsDetail(ctx, lyGoodsId, ch) p++ } //异步map最后转成map temp := make(map[string]interface{}) for i := 0; i < p; i++ { select { case GoodsRes := <-ch: GoodsRes.Range(func(k, v interface{}) bool { s, _ := k.(string) temp[s] = v return true }) case <-time.After(time.Second * 20): fmt.Println("协程超时", "sku", 1) } } return temp }