1.介绍
redis 官网推荐使用 redigo(https://github.com/gomodule/redigo), 但go-redis(https://github.com/go-redis/redis)使用的人更多, 并且go-redis 封装得更好。
2.安装
1
   | go get github.com/go-redis/redis/v8
 
  | 
 
3. 配置
3.1 编辑主配置
文件位置:./config.yaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | app:   ... log:   ... mysql:   ... jwt:   ... redis:   host: 127.0.0.1   port: 6379   password:    defaultDB: 0    dialTimeout: 5s 
 
  | 
 
3.2 新增结构体
文件位置:  ./config/redis.go
1 2 3 4 5 6 7 8 9 10 11
   | 
 
  package config
  type redis struct { 	Addr        string        `yaml:"addr"` 	Password    string        `yaml:"password"` 	DefaultDB   int           `yaml:"defaultDB"` 	DialTimeout time.Duration `yaml:"dialTimeout"` }
 
  | 
 
3.3 嵌入主配置
编辑文件:./config/app.go
1 2 3 4 5
   |  type ServerConfig struct { 	... 	Redis redis `yaml:"redis"` }
 
  | 
 
3.4 定义全局变量
编辑文件:./global/global.go
1 2 3 4 5
   |  var (   ... 	GvaRedis *redis.Client  )
 
  | 
 
4. 集成代码
4.1 集成入口
编辑文件:./main.go
1 2 3 4 5 6 7 8 9
   | func init() { 	... 	 	initialize.InitRedis() } func main() { 	 	... }
 
  | 
 
4.2 创建客户端
新建文件:./initialize/redis.go
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
   | 
 
  package initialize import ( 	"52lu/go-import-template/global" 	"context" 	"github.com/go-redis/redis/v8" )
  func InitRedis()  { 	 	redisClient := redis.NewClient(&redis.Options{ 		Addr:     global.GvaConfig.Redis.Addr, 		Password: global.GvaConfig.Redis.Password, 		DB:       global.GvaConfig.Redis.DefaultDB, 	}) 	 	timeoutCtx, cancelFunc := context.WithTimeout(context.Background(), global.GvaConfig.Redis.DialTimeout) 	defer cancelFunc() 	_, err := redisClient.Ping(timeoutCtx).Result() 	if err != nil { 		panic("redis初始化失败! "+err.Error()) 	} 	global.GvaRedis = redisClient }
 
  | 
 
5. 简单使用
5.1 注册路由
新增文件:./router/test_router.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   | 
 
  package router import ( 	v1 "52lu/go-import-template/api/v1" 	"github.com/gin-gonic/gin" )
  func InitTestRouter(engine *gin.Engine) { 	systemRouter := engine.Group("test") 	{ 		 		systemRouter.GET("redis", v1.RdTest) 	} }
 
  | 
 
5.2 绑定方法
新增文件:./api/v1/test_api.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   |  func RdTest(ctx *gin.Context)  { 	method, _ := ctx.GetQuery("type") 	var result string 	var err error 	switch method { 	case "get": 		result, err = global.GvaRedis.Get(ctx, "test").Result() 	case "set": 		result, err = global.GvaRedis.Set(ctx, "test", "hello word!", time.Hour).Result() 	} 	if err != nil { 		response.Error(ctx,err.Error()) 		return 	} 	response.OkWithData(ctx,result) }
 
  | 
 
5.3 请求示例
1 2 3 4
   | ➜ curl -X GET http://127.0.0.1:8080/test/redis?type=set {"code":0,"msg":"请求成功","data":"OK"} ➜ curl -X GET http://127.0.0.1:8080/test/redis?type=get {"code":0,"msg":"请求成功","data":"hello word!"}
 
  |