roomManager.go 1.94 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 68 69 70 71 72 73 74 75 76 77 78 79
package manager

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"hilo-userCenter/common/mylogrus"
	"log"
	"time"
)

func getRoomUserKey(groupId string) string {
	return fmt.Sprintf("room:%v", groupId)
}

type RoomManager struct {
	Ctx         context.Context
	RedisClient *redis.Client
}

func (m *RoomManager) AddRoomUser(uid uint64, groupId string) error {
	key := getRoomUserKey(groupId)
	err := m.RedisClient.ZAdd(m.Ctx, key, &redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: fmt.Sprintf("%d", uid),
	}).Err()
	if err != nil {
		mylogrus.MyLog.Errorf("AddRoomUser fail:%v", err)
		return nil
	}
	return err
}

func (m *RoomManager) DelRoomUser(uid uint64, groupId string) error {
	key := getRoomUserKey(groupId)
	err := m.RedisClient.ZRem(m.Ctx, key, fmt.Sprintf("%d", uid)).Err()
	if err != nil {
		mylogrus.MyLog.Errorf("DelRoomUser fail:%v", err)
		return nil
	}
	return err
}

func (m *RoomManager) UpdateRoomUser(uid uint64, groupId string) error {
	key := getRoomUserKey(groupId)
	err := m.RedisClient.ZAdd(m.Ctx, key, &redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: fmt.Sprintf("%d", uid),
	}).Err()
	if err != nil {
		mylogrus.MyLog.Errorf("AddRoomUser fail:%v", err)
		return nil
	}
	return err
}

// 获取用户在房间的最后一次心跳
func (m *RoomManager) GetLastRoomUserHeartbeat(uid uint64, groupId string) (int64, error) {
	key := getRoomUserKey(groupId)
	tx, err := m.RedisClient.ZScore(m.Ctx, key, fmt.Sprintf("%d", uid)).Result()
	if err != nil && err != redis.Nil {
		mylogrus.MyLog.Errorf("GetLastRoomUserHeartbeat fail:%v", err)
		return 0, err
	}
	// redis nil means 0
	return int64(tx), nil
}

func (m *RoomManager) GetAll() *map[string]string {
	//ctx, _ := context.WithTimeout(m.Ctx, time.Millisecond*500)
	//result := m.RedisClient.Get(ctx, field)
	result, err := m.RedisClient.HGetAll(m.Ctx, user_key).Result()
	if err != nil {
		log.Printf("HGetAll error: %s\n", err.Error())
		return nil
	} else {
		return &result
	}
}