go gin封装redis

发布于 2022-09-01 22:29:51阅读 1429

封装

package cache

import (
	"fmt"
	"github.com/go-redis/redis"
	"time"
)

var RedisClient *redis.Client

func InitRedis() {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:         "localhost:6379",
		Password:     "",
		DB:           0,
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     10,
		PoolTimeout:  30 * time.Second,
	})
	ping, err := RedisClient.Ping().Result()
	if err == redis.Nil {
		fmt.Print("Redis异常")
	} else if err != nil {
		fmt.Print("失败:", err)
	} else {
		fmt.Print(ping)
	}
}

使用

model

package model

import (
	"gin-demo/api/core/cache"
	"strconv"
)

func Key(id int) string {
	return "gin.www.admin." + strconv.Itoa(id) + ".token"
}

func GetToken(id int) (string, error) {
	key := Key(id)
	token, err := cache.RedisClient.Get(key).Result()
	return token, err
}

controller

	//model.SetToken(1, true, 0)
	token, err := model.GetToken(1)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(token)

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验