user.go 4.47 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
package rpc

import (
	"encoding/json"
	"fmt"
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/mylogrus"
	"git.hilo.cn/hilo-common/resource/consul"
	"git.hilo.cn/hilo-common/resource/mysql"
	"github.com/hashicorp/consul/api"
	"math/rand"
)

const (
	defaultUserConsulName   = "hiloUser"
	defaultUserServerScheme = "http"
	defaultUserServerAddr   = "127.0.0.1:9040" // 默认内网转发,本地回环
)

var UserServerHost = []string{defaultUserServerAddr}

func init() {
	go func() {
		address := api.DefaultConfig().Address // 用consul api的default config
		if err := consul.RegisterWatcher("services", nil, address, func(serviceStatus map[string]map[string][]string) {
			if statusAddrs, ok := serviceStatus[defaultUserConsulName]; ok {
				healthAddrs, _ := statusAddrs[api.HealthPassing]
				l := len(healthAddrs)
				if l > 0 {
					mylogrus.MyLog.Infof("consul service update state:%v-%v", defaultUserConsulName, healthAddrs)
					UserServerHost = healthAddrs
				} else {
					mylogrus.MyLog.Warnf("consul service update local state:%v-%v", defaultUserConsulName, defaultUserServerAddr)
					UserServerHost = []string{defaultUserServerAddr} // 有其他问题都用默认的
				}
				for status := range statusAddrs {
					if status == api.HealthPassing {
						continue
					}
					mylogrus.MyLog.Warnf("consul service wrong state:%v-%v-%v", defaultUserConsulName, status, statusAddrs[status])
				}
			}
		}); err != nil {
			mylogrus.MyLog.Errorf("启动 consul 的watch监控失败")
		}
	}()
}

type CvUserLevel struct {
	UserId          mysql.ID `json:"userId"`          // 用户id
	WealthUserGrade uint32   `json:"wealthUserGrade"` //财富等级
	CharmUserGrade  uint32   `json:"charmUserGrade"`  //魅力等级
}

// 获取用户等级
func GetUserLevel(model *domain.Model, userId mysql.ID) (CvUserLevel, error) {
	level, err := MGetUserLevel(model, []mysql.ID{userId})
	if err != nil {
		return CvUserLevel{}, nil
	}
	return level[userId], nil
}

// 批量获取用户等级
func MGetUserLevel(model *domain.Model, userIds []mysql.ID) (map[mysql.ID]CvUserLevel, error) {
	type Response struct {
hujiebin's avatar
hujiebin committed
67 68 69
		Code    int                      `json:"code"`
		Message string                   `json:"message"`
		Data    map[mysql.ID]CvUserLevel `json:"data"`
hujiebin's avatar
hujiebin committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	}
	var res = make(map[mysql.ID]CvUserLevel)
	if len(userIds) <= 0 {
		return res, nil
	}
	var userIdsStr []string
	for _, userId := range userIds {
		userIdsStr = append(userIdsStr, fmt.Sprintf("%d", userId))
	}
	_url := fmt.Sprintf("%v://%v/inner/user/levels", defaultUserServerScheme, getUserHost())
	resp, err := HttpGet(model, _url, nil, map[string][]string{
		"ids": userIdsStr,
	})
	if err != nil {
		model.Log.Errorf("MGetUserLevel fail:%v", err)
		return res, err
	}
	response := new(Response)
	if err = json.Unmarshal(resp, response); err != nil {
		model.Log.Errorf("MGetUserLevel json fail:%v", err)
		return res, err
	}
	for userId, level := range response.Data {
		res[userId] = CvUserLevel{
			UserId:          level.UserId,
			WealthUserGrade: level.WealthUserGrade,
			CharmUserGrade:  level.CharmUserGrade,
		}
	}
	return res, nil
}

hujiebin's avatar
hujiebin committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
type CvUserBag struct {
	BagId      mysql.ID   `json:"bagId"`      // 背包id
	ResType    mysql.Type `json:"resType"`    // 道具类型 1:礼物道具
	ResId      mysql.ID   `json:"resId"`      // 道具资源id
	Name       string     `json:"name"`       // 资源名称
	DiamondNum mysql.Num  `json:"diamondNum"` // 钻石数量
	IconUrl    string     `json:"iconUrl"`    // icon url
	SvgaUrl    string     `json:"svgaUrl"`    // svga url
	Count      mysql.Num  `json:"count"`      // 拥有数量
	RemainDays int        `json:"remainDays"` // 有效天数
}

// 批量用户背包
func GetUserBag(model *domain.Model, bagId mysql.ID) (CvUserBag, error) {
	type Response struct {
		Code    int       `json:"code"`
		Message string    `json:"message"`
		Data    CvUserBag `json:"data"`
	}
	_url := fmt.Sprintf("%v://%v/inner/user/bag", defaultUserServerScheme, getUserHost())
	resp, err := HttpGet(model, _url, nil, map[string][]string{
		"bagId": {fmt.Sprintf("%d", bagId)},
	})
	if err != nil {
		model.Log.Errorf("GetUserBag fail:%v", err)
		return CvUserBag{}, err
	}
	response := new(Response)
	if err = json.Unmarshal(resp, response); err != nil {
		model.Log.Errorf("GetUserBag json fail:%v", err)
		return CvUserBag{}, err
	}
	return response.Data, nil
}

hujiebin's avatar
hujiebin committed
137 138 139 140 141 142
func getUserHost() string {
	l := len(UserServerHost)
	r := rand.Intn(l) // 随机一个
	mylogrus.MyLog.Infof("getHostUser:%v---%v", r, UserServerHost[r])
	return UserServerHost[r]
}