审查视图

pkg/infrastructure/xredis/redis.go 1.6 KB
tangxvhui authored
1
package xredis
tangxvhui authored
2 3 4

import (
	"context"
5
	"encoding/json"
tangxvhui authored
6
	"fmt"
7
	"reflect"
tangxvhui authored
8
	"strconv"
9 10
	"strings"
	"time"
tangxvhui authored
11 12

	"github.com/go-redis/redis/v8"
tangxvhui authored
13 14
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
tangxvhui authored
15 16 17 18
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
)

var rdb *redis.Client
tangxvhui authored
19
var rsync *redsync.Redsync
tangxvhui authored
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

func init() {
	host := constant.REDIS_HOST
	port := constant.REDIS_PORT
	auth := constant.REDIS_AUTH
	index := 0
	if constant.REDIS_DB != "" {
		indexDb := constant.REDIS_DB
		index, _ = strconv.Atoi(indexDb)
	}
	rdb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%v:%v", host, port),
		Password: auth,
		DB:       index, // use default DB
	})
	res := rdb.Ping(context.TODO())
	if res.Err() != nil {
		panic("redis not found")
	}
tangxvhui authored
39 40
	pool := goredis.NewPool(rdb)
	rsync = redsync.New(pool)
tangxvhui authored
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

func Set(key string, value interface{}, timeout time.Duration) error {
	valueOf := reflect.ValueOf(value)
	typeName := strings.ToLower(valueOf.Type().Name())
	var newValue interface{}
	if typeName == "string" || typeName == "int" || typeName == "int64" || typeName == "float64" {
		newValue = value
	} else {
		mBytes, err := json.Marshal(value)
		if err != nil {
			return err
		}
		newValue = string(mBytes)
	}

	err := rdb.Set(rdb.Context(), key, newValue, timeout*time.Second).Err()
	return err
}

func Get(key string) string {
	value, err := rdb.Get(rdb.Context(), key).Result()
	if err != nil {
		return ""
	}
	return value
}

func GetBytes(key string) ([]byte, error) {
	return rdb.Get(rdb.Context(), key).Bytes()
}

func Remove(key string) error {
	return rdb.Del(rdb.Context(), key).Err()
}