terminalManager.go 1.54 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
package manager

import (
	"context"
	"github.com/go-redis/redis/v8"
	"log"
	"strconv"
)

const (
	terminal_key = "terminal"
)

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

func (m *TerminalManager) GetTerminal(uid uint64) *string {
	field := strconv.FormatUint(uid, 10)
	//ctx, _ := context.WithTimeout(m.Ctx, time.Millisecond*500)
	//result := m.RedisClient.Get(ctx, field)
	result, err := m.RedisClient.HGet(m.Ctx, terminal_key, field).Result()
	if err != nil {
		log.Printf("HGet error %s\n", err.Error())
		return nil
	}
	return &result
}

func (m *TerminalManager) SetTerminal(uid uint64, value string) error {
	field := strconv.FormatUint(uid, 10)
	result, err := m.RedisClient.HSet(m.Ctx, terminal_key, field, value).Result()

	if err != nil {
		log.Printf("HSet error %s\n")
	} else {
		log.Printf("HSet %s:%s result: %d\n", terminal_key, field, result)
	}
	return err
}

func (m *TerminalManager) RemoveTerminal(uid uint64) error {
	field := strconv.FormatUint(uid, 10)
	result, err := m.RedisClient.HDel(m.Ctx, terminal_key, field).Result()

	if err != nil {
		log.Printf("HDel error: %s\n", err.Error())
	} else {
		log.Printf("HDel %s return %d\n", field, result)
	}
	return err
}

func (m *TerminalManager) 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, terminal_key).Result()
	if err != nil {
		log.Printf("HGetAll error: %s\n", err.Error())
		return nil
	} else {
		return &result
	}
}