集成Redis

1991/6/26 Gin框架

# 1.介绍

redis官网推荐使用redigo(https://github.com/gomodule/redigo),截止到今天Github Start是8.2kgo-redis(https://github.com/go-redis/redis)使用的人更多, 并且go-redis封装得更好。截止到今天Github Start 是12.1k

# 1.1 集成流程

# 2.安装

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

# 3. 配置

# 3.1 编辑主配置

文件位置:./config.yaml

app:
  ...
log:
  ...
mysql:
  ...
jwt:
  ...
redis:
  host: 127.0.0.1
  port: 6379
  password: # 密码(可为空)
  defaultDB: 0 # 默认DB
  dialTimeout: 5s #redis连接超时时间.默认5s
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.2 新增结构体

文件位置: ./config/redis.go

/**
 * @Description redis配置
 **/
package config

type redis struct {
 Addr        string        `yaml:"addr"`
 Password    string        `yaml:"password"`
 DefaultDB   int           `yaml:"defaultDB"`
 DialTimeout time.Duration `yaml:"dialTimeout"`
}
1
2
3
4
5
6
7
8
9
10
11

# 3.3 嵌入主配置

编辑文件:./config/app.go

// ServerConfig 配置信息
type ServerConfig struct {
 ...
 Redis redis `yaml:"redis"`
}
1
2
3
4
5

# 3.4 定义全局变量

编辑文件:./global/global.go

// 变量
var (
  ...
 GvaRedis *redis.Client //Redis客户端
)
1
2
3
4
5

# 4. 集成代码

# 3.1 集成入口

编辑文件:./main.go

func init() {
 ...
 // 初始化redis
 initialize.InitRedis()
}
func main() {
 // 启动服务
 ...
}
1
2
3
4
5
6
7
8
9

# 4.2 创建客户端

新建文件:./initialize/redis.go

/**
 * @Description 初始化redis
 **/
package initialize
import (
 "52lu/go-import-template/global"
 "context"
 "github.com/go-redis/redis/v8"
)
// 初始化redis客户端
func InitRedis()  {
 // 创建
 redisClient := redis.NewClient(&redis.Options{
  Addr:     global.GvaConfig.Redis.Addr,
  Password: global.GvaConfig.Redis.Password,
  DB:       global.GvaConfig.Redis.DefaultDB,
 })
 // 使用超时上下文,验证redis
 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
}
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

# 5. 简单使用

# 5.1 注册路由

新增文件:./router/test_router.go

/**
 * @Description 测试路由
 **/
package router
import (
 v1 "52lu/go-import-template/api/v1"
 "github.com/gin-gonic/gin"
)
// 测试路由
func InitTestRouter(engine *gin.Engine) {
 systemRouter := engine.Group("test")
 {
  // redis测试使用
  systemRouter.GET("redis", v1.RdTest)
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 5.2 绑定方法

新增文件:./api/v1/test_api.go

// 验证redis
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)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 5.3 请求示例

➜ 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!"}
1
2
3
4

# 5.4 更多使用方法

Go常用包:操作redis开源库(go-redis)