• Golang Redis连接池封装


    1.创建连接池方法文件

    1. package dao
    2. import (
    3. "fmt"
    4. "github.com/gomodule/redigo/redis"
    5. "gopkg.in/ini.v1"
    6. "os"
    7. "sync"
    8. "time"
    9. )
    10. var once sync.Once
    11. // RedisClient Redis 服务
    12. type RedisClient struct {
    13. Client *redis.Pool
    14. }
    15. //Redis 全局 Redis
    16. var RedisPool *RedisClient
    17. //ConnectRedis 连接 redis 数据库,设置全局的 Redis 对象
    18. func ConnectRedis() {
    19. config, err := ini.Load("./config/app.ini")
    20. if err != nil {
    21. //失败
    22. fmt.Printf("Fail to read file: %v", err)
    23. os.Exit(1)
    24. }
    25. address := config.Section("redis").Key("address").String()
    26. password := config.Section("redis").Key("password").String()
    27. db, _ := config.Section("redis").Key("db").Int()
    28. once.Do(func() {
    29. RedisPool = NewClient(address, password, db)
    30. })
    31. con_err := RedisPool.Ping()
    32. if con_err != nil {
    33. panic(con_err)
    34. }
    35. }
    36. // NewClient 创建一个新的 redis 连接
    37. func NewClient(address string, password string, db int) *RedisClient {
    38. // 初始化自定的 RedisClient 实例
    39. rds := &RedisClient{}
    40. // 使用 redis 库里的 NewClient 初始化连接
    41. rds.Client = &redis.Pool{
    42. MaxIdle: 100, //最大空闲
    43. MaxActive: 1000, //最大连接
    44. IdleTimeout: time.Duration(60) * time.Second,
    45. Wait: true,
    46. Dial: func() (redis.Conn, error) {
    47. c, err := redis.Dial(
    48. "tcp",
    49. address,
    50. redis.DialPassword(password),
    51. redis.DialDatabase(int(db)),
    52. redis.DialConnectTimeout(time.Duration(60)*time.Second),
    53. redis.DialReadTimeout(time.Duration(60)*time.Second),
    54. redis.DialWriteTimeout(time.Duration(60)*time.Second),
    55. )
    56. if err != nil {
    57. return nil, err
    58. }
    59. return c, err
    60. },
    61. }
    62. return rds
    63. }
    64. // Ping 用以测试 redis 连接是否正常
    65. func (rds *RedisClient) Ping() error {
    66. _, err := rds.Client.Get().Do("ping")
    67. return err
    68. }
    69. // Set 存储 key 对应的 value,且设置 expiration 过期时间(单位纳秒)
    70. func (rds *RedisClient) Setex(key string, expiration int, value interface{}) bool {
    71. conn := rds.Client.Get()
    72. defer conn.Close()
    73. if _, err := conn.Do("setex", key, expiration, value); err != nil {
    74. fmt.Println(err)
    75. return false
    76. }
    77. return true
    78. }
    79. //
    80. //Get 获取 key 对应的 value
    81. func (rds *RedisClient) Get(key string) string {
    82. conn := rds.Client.Get()
    83. defer conn.Close()
    84. result, err := redis.String(conn.Do("Get", key))
    85. if err != nil {
    86. return ""
    87. }
    88. return result
    89. }
    90. //Get 获取 key 对应的 value
    91. func (rds *RedisClient) Rpop(key string) (string, error) {
    92. conn := rds.Client.Get()
    93. defer conn.Close()
    94. result, err := redis.String(conn.Do("Rpop", key))
    95. if err != nil {
    96. return "", err
    97. }
    98. return result, nil
    99. }

    2.配置文件

    1. app_name = go-gin
    2. [mysql]
    3. ip = 127.0.0.1
    4. port = 3306
    5. user = root
    6. password = root
    7. database = test
    8. prefix = tt_
    9. #最大连接数
    10. MaxIdleConns = 500
    11. #最大空闲
    12. MaxOpenConns = 50
    13. [redis]
    14. address = 127.0.0.1:6379
    15. password = 123456
    16. db = 7

    3.调用方法

    1. func main() {
    2. dao.ConnectRedis() //初始化连接redis
    3. defer dao.RedisPool.Client.Close() //退出前执行关闭
    4. res, err := dao.RedisPool.Rpop("aaa")
    5. if err != nil {
    6. fmt.Println(err)
    7. }
    8. fmt.Println(res)
    9. }

  • 相关阅读:
    机器学习项目实战合集列表
    kotlin基础教程:<3>函数的高级用法和字符串的基础操作
    Swift爬虫程序
    Go基础学习【2】
    Android 字符串 占位符
    Hadoop搭建HA遇到的坑
    STM32 HAL库高级定时器输入捕获脉宽测量
    C++实现集群聊天服务器
    线性代数学习笔记7-3:解微分方程、矩阵的指数函数(特征值的应用)
    HashTable和HashMap的区别
  • 原文地址:https://blog.csdn.net/qq_36514588/article/details/126389552