package service import ( "context" "fmt" "time" "vote-admin-api/config" "vote-admin-api/global" ) type UserService struct { } // AddUserVoteDayCache 新增用户每日投票记录缓存 // t 1:文章 2:视频 func (r *UserService) AddUserVoteDayCache(userId, id int64, t int) bool { now := time.Now() redisKey := "UserVoteDay" + fmt.Sprintf("%d", userId) + fmt.Sprintf("%d", id) + now.Format("2006-01-02") + fmt.Sprintf("%d", t) // 缓存过期时间 year, month, day := now.Date() location := now.Location() validTime := time.Date(year, month, day, 23, 59, 59, 0, location) duration := validTime.Sub(now) if duration < 0 { return false } if config.C.Env == "dev" { duration = 60 * 5 * time.Second } // 添加缓存 _, err := global.Redis.Set(context.Background(), redisKey, "1", duration).Result() if err != nil { return false } return true } // CheckUserVoteDay 检测用户今日是否投票 // t 1:文章 2:视频 func (r *UserService) CheckUserVoteDay(userId, id int64, t int) bool { if t != 1 && t != 2 { return false } now := time.Now() redisKey := "UserVoteDay" + fmt.Sprintf("%d", userId) + fmt.Sprintf("%d", id) + now.Format("2006-01-02") + fmt.Sprintf("%d", t) res, _ := global.Redis.Get(context.Background(), redisKey).Result() if res == "" { return false } if res == "1" { return true } return false //if res == "" { // // 是否已投票(1:已投票 0:未投票) // isVote := "0" // if t == 1 { // // 文章 // maps := make(map[string]interface{}) // maps["article_id"] = id // maps["user_id"] = userId // maps["voted_at"] = now.Format("2006-01-02") // // articleVoteDayDao := dao.ArticleVoteDayDao{} // articleVoteDay, _ := articleVoteDayDao.GetArticleVoteDayById(id) // if articleVoteDay != nil { // isVote = "1" // } // } // // if t == 2 { // // 视频 // maps := make(map[string]interface{}) // maps["article_id"] = id // maps["user_id"] = userId // maps["voted_at"] = now.Format("2006-01-02") // // videoVoteDayDao := dao.VideoVoteDayDao{} // videoVoteDay, _ := videoVoteDayDao.GetVideoVoteDayById(id) // if videoVoteDay != nil { // isVote = "1" // } // } // // // 添加缓存 // if isVote == "1" { // result := r.AddUserVoteDayCache(userId, id, t) // if result == false { // return false // } // } // // res = isVote //} // //if res == "0" { // return false //} else { // return true //} }