0


Go语学习笔记 - redis单节点模式 | Web框架Gin(十二)

学习笔记,写到哪是哪。

接着上一篇文章:Go语学习笔记 - gorm使用 - 事务操作 | Web框架Gin(十一)_剑客阿良_ALiang的博客-CSDN博客

在前面几篇主要是说gorm对数据库的一些操作,后面可能还会继续。

本文主要写一下redis单节点的初始化和操作。

项目地址:github地址

在配置文件中增加redis配置。

[redis]
urls = ["xxxxxxxx:6379"]
password = "xxxxxx"

增加toml中RedisConfig结构体,在config/toml/toml_config.go增加。

package toml

import (
    "fmt"
    "github.com/spf13/viper"
)

type TomlConfig struct {
    AppName string
    Log     LogConfig
    Mysql   MysqlConfig
    Redis   RedisConfig
}

// 日志保存地址
type LogConfig struct {
    Path  string
    Level string
}

// Mysql配置
type MysqlConfig struct {
    Host     string
    User     string
    Password string
    DbName   string
    Port     int64
}

type RedisConfig struct {
    Urls     []string
    Password string
}

var c TomlConfig

func init() {
    // 设置文件名
    viper.SetConfigName("config")
    // 设置文件类型
    viper.SetConfigType("toml")
    // 设置文件路径,可以多个viper会根据设置顺序依次查找
    viper.AddConfigPath(".")
    viper.AutomaticEnv()
    err := viper.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("fatal error config file: %s", err))
    }

    viper.Unmarshal(&c)
}
func GetConfig() TomlConfig {
    return c
}

增加redis初始化,在config下增加redis目录,增加redis_init.go文件,代码如下:

package redis

import (
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
    "learn-gin/config/toml"
    "time"
)

var Redis *RedisClient

// RedisClient extend client and have itself func
type RedisClient struct {
    *redis.Client
}

// Init the redis client
func NewRedisClient() error {
    if Redis != nil {
        return nil
    }
    client := redis.NewClient(&redis.Options{
        Addr:     toml.GetConfig().Redis.Urls[0],
        Password: toml.GetConfig().Redis.Password,
        DB:       0,
        PoolSize: 10, //连接池大小
        //超时
        DialTimeout:  5 * time.Second, //连接建立超时时间,默认5秒。
        ReadTimeout:  3 * time.Second, //读超时,默认3秒, -1表示取消读超时
        WriteTimeout: 3 * time.Second, //写超时,默认等于读超时
        PoolTimeout:  4 * time.Second, //当所有连接都处在繁忙状态时,客户端等待可用连接的最大等待时长,默认为读超时+1秒。

        //闲置连接检查包括IdleTimeout,MaxConnAge
        IdleCheckFrequency: 60 * time.Second, //闲置连接检查的周期,默认为1分钟,-1表示不做周期性检查,只在客户端获取连接时对闲置连接进行处理。
        IdleTimeout:        5 * time.Minute,  //闲置超时,默认5分钟,-1表示取消闲置超时检查
        MaxConnAge:         0 * time.Second,  //连接存活时长,从创建开始计时,超过指定时长则关闭连接,默认为0,即不关闭存活时长较长的连接

        //命令执行失败时的重试策略
        MaxRetries:      0,                      //命令执行失败时,最多重试多少次,默认为0即不重试
        MinRetryBackoff: 8 * time.Millisecond,   //每次计算重试间隔时间的下限,默认8毫秒,-1表示取消间隔
        MaxRetryBackoff: 512 * time.Millisecond, //每次计算重试间隔时间的上限,默认512毫秒,-1表示取消间隔

        //仅当客户端执行命令时需要从连接池获取连接时,如果连接池需要新建连接时则会调用此钩子函数
        OnConnect: func(ctx context.Context, conn *redis.Conn) error {
            fmt.Printf("创建新的连接: %v\n", conn)
            return nil
        },
    })

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    _, err := client.Ping(ctx).Result()
    if err != nil {
        return err
    }
    if err != nil {
        return err
    }
    Redis = &RedisClient{client}
    return nil
}

// init the redis  client
func init() {
    err := NewRedisClient()
    if err != nil {
        fmt.Println("failed to connect redis client")
    }
}

// set the string to redis,the expire default is seven days
func (redis *RedisClient) SSet(key string, value interface{}) *redis.StatusCmd {
    return redis.Set(context.TODO(), key, value, 24*time.Hour)
}

// get the string value by key
func (redis *RedisClient) SGet(key string) string {
    return redis.Get(context.TODO(), key).String()
}

// close the redis client
func (redis *RedisClient) Close() {
    redis.Close()
}

// get the redis client,if client not initialization
// and create the redis client
func GetRedisClient() (*RedisClient, error) {
    if Redis == nil {
        err := NewRedisClient()
        if err != nil {
            return nil, err
        }
        return Redis, nil
    }
    return Redis, nil
}

在使用的时候可以通过GetRedisClient方法获取已经构建的对象。

编写Redis测试方法,在services下增加redis_service.go文件,代码如下:

package services

import (
    "context"
    "learn-gin/app/pojo/rsp"
    "learn-gin/config/log"
    "learn-gin/config/redis"
    "time"
)

type RedisService interface {
    TestRedisInit() rsp.ResponseMsg
}

type RedisImpl struct {
}

//测试redis初始化使用
func (r RedisImpl) TestRedisInit() rsp.ResponseMsg {
    log.Logger.Info("测试redis初始化使用")
    _redis, _err := redis.GetRedisClient()
    if _err != nil {
        log.Logger.Panic("获取redis连接异常", log.Any("error", _err.Error()))
    }
    _err = _redis.Set(context.TODO(), "haha", 100, 10*time.Second).Err()
    if _err != nil {
        log.Logger.Panic("设置缓存失败")
    }
    _v, _ := _redis.Get(context.TODO(), "haha").Result()

    log.Logger.Debug("haha缓存为:", log.String("v", _v))
    return *rsp.SuccessMsg("测试缓存")
}

验证一下

小结

下一章将集群,我在测试集群的时候走了一点小坑,可能会单独开一篇去讲。


本文转载自: https://blog.csdn.net/zhiweihongyan1/article/details/125680693
版权归原作者 剑客阿良_ALiang 所有, 如有侵权,请联系我们删除。

“Go语学习笔记 - redis单节点模式 | Web框架Gin(十二)”的评论:

还没有评论