package recommend import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "gitea.ddegame.cn/open/servicebase/pkg/cache" "github.com/anxpp/beego" "github.com/anxpp/beego/logs" redis "github.com/redis/go-redis/v9" ) const ( keyUser = "user" redisKey = "RECOMMEND" ) type ItemScore struct { Key string Score float64 } type recommendRes struct { Code int `json:"code"` Data []ItemScore `json:"data"` Msg string `json:"msg"` } func GetRecommendUserList(page, size int, skillId string, input map[string]string) (list []string) { rk := fmt.Sprintf("%s_%s_%s_%s", redisKey, keyUser, skillId, input["user.id"]) redisClient := cache.GetCommonRedisInstance().RedisClient // 更新缓存 存在缓存穿透 if page == 0 { members := recommendList(keyUser, skillId, input) var mList []redis.Z for _, item := range members { mList = append(mList, redis.Z{ Score: item.Score, Member: item.Key, }) } if len(mList) > 0 { redisClient.ZAdd(cache.Ctx(), rk, mList...) } } list, _ = redisClient.ZRevRange(cache.Ctx(), rk, int64(page*size), int64((page+1)*size-1)).Result() return } func recommendList(key, group string, input map[string]string) (list []ItemScore) { logs.Info("load recommend info from recommend service.") url := fmt.Sprintf("%s%s?group=%s", beego.AppConfig.String("recommendServiceUrl"), key, group) requestBody, _ := json.Marshal(input) resp, err := http.Post(url, "application/json;charset=UTF-8", bytes.NewReader(requestBody)) if err != nil { logs.Info(err.Error()) } if nil == resp { return } defer func() { _ = resp.Body.Close() }() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } logs.Info(string(body)) var res recommendRes _ = json.Unmarshal(body, &res) if res.Code != 6000 { logs.Info(res.Msg) } return res.Data }