medal.go 1.6 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
package user_m

import (
	"context"
	"fmt"
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/mylogrus"
	"git.hilo.cn/hilo-common/resource/mysql"
	"git.hilo.cn/hilo-common/resource/redisCli"
	"git.hilo.cn/hilo-common/utils"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

//用户道具
type UserMedal struct {
	mysql.Entity
	*domain.Model `gorm:"-"`
	UserId        mysql.ID
	MedalId       uint32
	//MedalType     res_m2.ResMedalType
	//Scope         res_m2.ResMedalScope
	EndTime *time.Time
}

func (um *UserMedal) Create(db *gorm.DB, day int) error {
	err := db.Clauses(clause.OnConflict{
		DoUpdates: clause.Assignments(map[string]interface{}{
			"end_time": gorm.Expr("DATE_ADD(GREATEST(end_time,NOW()), INTERVAL ? DAY);", day)}),
	}).Create(um).Error
	// 删除勋章缓存, 延迟删除
	DelUserMedalMergeCacheDelay(um.UserId)
	return err
}

// 删除勋章缓存, 延迟删除
func DelUserMedalMergeCacheDelay(userId mysql.ID) {
	go func() {
		defer utils.CheckGoPanic()
		time.Sleep(time.Second * 5)
		DelUserMedalMergeCache(userId)
	}()
}
func DelUserMedalMergeCache(userId mysql.ID) error {
	err := DelCache(getUserMedalMergeKey(userId))
	if err != nil {
		mylogrus.MyLog.Errorf("DetUserMedalMerge err:%s, userId:%v", err, userId)
		return err
	}
	return nil
}

const userMedalMerge = "user:medalMerge:%d" // 勋章

func getUserMedalMergeKey(userId uint64) string {
	return fmt.Sprintf(userMedalMerge, userId)
}

func DelCache(key string) error {
	err := redisCli.GetRedis().Del(context.Background(), key).Err()
	if err != nil {
		mylogrus.MyLog.Errorf("DelCache key:%s, err:%s", key, err)
		return err
	}
	return nil
}