0


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

学习笔记,写到哪是哪。

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

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

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

项目地址:github地址

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

  1. [redis]
  2. urls = ["xxxxxxxx:6379"]
  3. password = "xxxxxx"

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

  1. package toml
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. )
  6. type TomlConfig struct {
  7. AppName string
  8. Log LogConfig
  9. Mysql MysqlConfig
  10. Redis RedisConfig
  11. }
  12. // 日志保存地址
  13. type LogConfig struct {
  14. Path string
  15. Level string
  16. }
  17. // Mysql配置
  18. type MysqlConfig struct {
  19. Host string
  20. User string
  21. Password string
  22. DbName string
  23. Port int64
  24. }
  25. type RedisConfig struct {
  26. Urls []string
  27. Password string
  28. }
  29. var c TomlConfig
  30. func init() {
  31. // 设置文件名
  32. viper.SetConfigName("config")
  33. // 设置文件类型
  34. viper.SetConfigType("toml")
  35. // 设置文件路径,可以多个viper会根据设置顺序依次查找
  36. viper.AddConfigPath(".")
  37. viper.AutomaticEnv()
  38. err := viper.ReadInConfig()
  39. if err != nil {
  40. panic(fmt.Errorf("fatal error config file: %s", err))
  41. }
  42. viper.Unmarshal(&c)
  43. }
  44. func GetConfig() TomlConfig {
  45. return c
  46. }

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

  1. package redis
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/go-redis/redis/v8"
  6. "learn-gin/config/toml"
  7. "time"
  8. )
  9. var Redis *RedisClient
  10. // RedisClient extend client and have itself func
  11. type RedisClient struct {
  12. *redis.Client
  13. }
  14. // Init the redis client
  15. func NewRedisClient() error {
  16. if Redis != nil {
  17. return nil
  18. }
  19. client := redis.NewClient(&redis.Options{
  20. Addr: toml.GetConfig().Redis.Urls[0],
  21. Password: toml.GetConfig().Redis.Password,
  22. DB: 0,
  23. PoolSize: 10, //连接池大小
  24. //超时
  25. DialTimeout: 5 * time.Second, //连接建立超时时间,默认5秒。
  26. ReadTimeout: 3 * time.Second, //读超时,默认3秒, -1表示取消读超时
  27. WriteTimeout: 3 * time.Second, //写超时,默认等于读超时
  28. PoolTimeout: 4 * time.Second, //当所有连接都处在繁忙状态时,客户端等待可用连接的最大等待时长,默认为读超时+1秒。
  29. //闲置连接检查包括IdleTimeout,MaxConnAge
  30. IdleCheckFrequency: 60 * time.Second, //闲置连接检查的周期,默认为1分钟,-1表示不做周期性检查,只在客户端获取连接时对闲置连接进行处理。
  31. IdleTimeout: 5 * time.Minute, //闲置超时,默认5分钟,-1表示取消闲置超时检查
  32. MaxConnAge: 0 * time.Second, //连接存活时长,从创建开始计时,超过指定时长则关闭连接,默认为0,即不关闭存活时长较长的连接
  33. //命令执行失败时的重试策略
  34. MaxRetries: 0, //命令执行失败时,最多重试多少次,默认为0即不重试
  35. MinRetryBackoff: 8 * time.Millisecond, //每次计算重试间隔时间的下限,默认8毫秒,-1表示取消间隔
  36. MaxRetryBackoff: 512 * time.Millisecond, //每次计算重试间隔时间的上限,默认512毫秒,-1表示取消间隔
  37. //仅当客户端执行命令时需要从连接池获取连接时,如果连接池需要新建连接时则会调用此钩子函数
  38. OnConnect: func(ctx context.Context, conn *redis.Conn) error {
  39. fmt.Printf("创建新的连接: %v\n", conn)
  40. return nil
  41. },
  42. })
  43. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  44. defer cancel()
  45. _, err := client.Ping(ctx).Result()
  46. if err != nil {
  47. return err
  48. }
  49. if err != nil {
  50. return err
  51. }
  52. Redis = &RedisClient{client}
  53. return nil
  54. }
  55. // init the redis client
  56. func init() {
  57. err := NewRedisClient()
  58. if err != nil {
  59. fmt.Println("failed to connect redis client")
  60. }
  61. }
  62. // set the string to redis,the expire default is seven days
  63. func (redis *RedisClient) SSet(key string, value interface{}) *redis.StatusCmd {
  64. return redis.Set(context.TODO(), key, value, 24*time.Hour)
  65. }
  66. // get the string value by key
  67. func (redis *RedisClient) SGet(key string) string {
  68. return redis.Get(context.TODO(), key).String()
  69. }
  70. // close the redis client
  71. func (redis *RedisClient) Close() {
  72. redis.Close()
  73. }
  74. // get the redis client,if client not initialization
  75. // and create the redis client
  76. func GetRedisClient() (*RedisClient, error) {
  77. if Redis == nil {
  78. err := NewRedisClient()
  79. if err != nil {
  80. return nil, err
  81. }
  82. return Redis, nil
  83. }
  84. return Redis, nil
  85. }

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

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

  1. package services
  2. import (
  3. "context"
  4. "learn-gin/app/pojo/rsp"
  5. "learn-gin/config/log"
  6. "learn-gin/config/redis"
  7. "time"
  8. )
  9. type RedisService interface {
  10. TestRedisInit() rsp.ResponseMsg
  11. }
  12. type RedisImpl struct {
  13. }
  14. //测试redis初始化使用
  15. func (r RedisImpl) TestRedisInit() rsp.ResponseMsg {
  16. log.Logger.Info("测试redis初始化使用")
  17. _redis, _err := redis.GetRedisClient()
  18. if _err != nil {
  19. log.Logger.Panic("获取redis连接异常", log.Any("error", _err.Error()))
  20. }
  21. _err = _redis.Set(context.TODO(), "haha", 100, 10*time.Second).Err()
  22. if _err != nil {
  23. log.Logger.Panic("设置缓存失败")
  24. }
  25. _v, _ := _redis.Get(context.TODO(), "haha").Result()
  26. log.Logger.Debug("haha缓存为:", log.String("v", _v))
  27. return *rsp.SuccessMsg("测试缓存")
  28. }

验证一下

小结

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


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

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

还没有评论