GIN框架初始化Redis

24 阅读1分钟

在Web应用中随着访问量的逐渐提高,使用关系型数据库的站点会遇到一些性能上的瓶颈——源头一般是磁盘的I/O。如今对网站的需求主要体现在低延迟的读写速度、支持海量的数据和流量、大规模集群的管理和运营成本的考量。而Redis在内存中运行,性能高效、支持分布式可扩展性强、键值对存储这些特征使其成为当前很最欢迎的NoSQL数据库之一。

安装

go get -u github.com/go-redis/redis/v8

定义配置项

redis:
  host: 127.0.0.1:6379
  db: 0
  password:
type Redis struct {
	Host        string
	Password    string
	DB          int
	IdleTimeout time.Duration
}

初始化redis

package redis
 
import (
	"context"
	"time"
  "leo-gin/config"

	"github.com/go-redis/redis/v8"
)
 
var (
	MyRedis *redis.Client
	ctx     = context.Background()
)
 
func Setup() {
  redConfig := config.Conf.Redis
	MyRedis = redis.NewClient(&redis.Options{
		Addr:     redConfig.Host,
		Password: redConfig.Password, // no password set
		DB:       redConfig.DB,       // use default DB
	})
	_, err := MyRedis.Ping(ctx).Result()
	if err != nil {
		config.Error("Redis connect ping failed, err:", err)
		return
	}
	config.Info("Redis connect succeeded")
	return
}
func SetRedis(key string, value string, t int64) bool {
	expire := time.Duration(t) * time.Second
	if err := MyRedis.Set(ctx, key, value, expire).Err(); err != nil {
		return false
	}
	return true
}
 
func GetRedis(key string) string {
	result, err := MyRedis.Get(ctx, key).Result()
	if err != nil {
		return ""
	}
	return result
}
 
func DelRedis(key string) bool {
	_, err := MyRedis.Del(ctx, key).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func ExpireRedis(key string, t int64) bool {
	// 延长过期时间
	expire := time.Duration(t) * time.Second
	if err := MyRedis.Expire(ctx, key, expire).Err(); err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

在 main.go 的 init 中 调用Setup

// redis 初始化
	redis.Setup()

Redis服务器安装

MacOS (使用Homebrew)

# 安装Redis
brew install redis

# 启动Redis服务
brew services start redis

# 验证是否启动成功
redis-cli ping  # 应返回 PONG

Docker快速启动

docker run -d -p 6379:6379 --name gin-redis redis:alpine