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 } }