redisServer.go 885 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package server
  2. import (
  3. "context"
  4. "github.com/redis/go-redis/v9"
  5. "go_zh/config"
  6. "time"
  7. )
  8. type RedisServer struct {
  9. rdb *redis.Client
  10. }
  11. // 定义单例实例,但不在包级别初始化
  12. var redisServerInstance *RedisServer
  13. var ctx = context.Background()
  14. // 使用init函数初始化单例实例
  15. func init() {
  16. redisServerInstance = &RedisServer{
  17. rdb: config.Rdb,
  18. }
  19. }
  20. // 获取单例实例的方法
  21. func GetRedisServerInstance() *RedisServer {
  22. return redisServerInstance
  23. }
  24. func (r *RedisServer) SetStr(key string, val string, timeout int) bool {
  25. err := r.rdb.Set(ctx, key, val, time.Duration(timeout)*time.Second).Err()
  26. if err != nil {
  27. return false
  28. }
  29. return true
  30. }
  31. func (r *RedisServer) GetStr(key string) string {
  32. if key == "" {
  33. return ""
  34. }
  35. ctx := context.Background()
  36. val, err := r.rdb.Get(ctx, key).Result()
  37. if err != nil {
  38. return ""
  39. }
  40. return val
  41. }