Golang
主页 > 脚本 > Golang >

Golang使用Redis与连接池方式

2024-06-02 | 佚名 | 点击:

Golang使用Redis与连接池

使用下载go的redis包go get github.com/gomodule/redigo/redis 如果网不好的话就很费劲了

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

27

28

29

30

31

32

33

34

35

36

37

38

package main

 

import (

    "fmt"

    "github.com/gomodule/redigo/redis" // 引入redis包

)

 

func main() {

    //连接数据源

    rediss, err := redis.Dial("tcp", "127.0.01:6379")

 

    if err != nil {

        fmt.Println("连接异常", err)

    }

 

    //插入string数据

    test, err := rediss.Do("set", "test", "hi")

    if err != nil {

        fmt.Println("插入数据失败", err)

    }

    fmt.Println(test)

 

    //读取string数据

    str, err := redis.String(rediss.Do("get", "test"))

    fmt.Println(str)

 

    //hash 类型

    do, _ := rediss.Do("hset", "hh", "name", "zhangsn")

    fmt.Println(do)

    hh, _ := redis.String(rediss.Do("hget", "hh", "name"))

    fmt.Println(hh)

 

    //设置key 过期时间

    rediss.Do("expire", "hh", 1)

 

    //关闭redis

    rediss.Close()

}

redis数据源连接池

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

27

28

29

30

31

32

33

34

35

package main

 

import (

    "fmt"

    "github.com/gomodule/redigo/redis" // 引入redis包

)

 

var pool *redis.Pool

 

func init() {

    pool = &redis.Pool{

        MaxIdle:     8,   //最大空闲连接数

        MaxActive:   0,   //表示和数据库最大连接数。0表示没有限制

        IdleTimeout: 100, //最大空闲时间

        Dial: func() (redis.Conn, error) { //初始化连接 redis 地址

            return redis.Dial("tcp", "127.0.01:6379")

        },

    }

}

func main() {

 

    //获取连接

    conn := pool.Get()

    //插入数据

    do, err := conn.Do("set", "11", "11")

    if err != nil {

        fmt.Println("插入失败", err)

    }

 

    fmt.Println(do)

 

    //关闭redis

    conn.Close()

 

}

Golang Redis连接池封装

创建连接池方法文件

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

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

package dao

  

import (

    "fmt"

    "github.com/gomodule/redigo/redis"

    "gopkg.in/ini.v1"

    "os"

    "sync"

    "time"

)

  

var once sync.Once

  

// RedisClient Redis 服务

type RedisClient struct {

    Client *redis.Pool

}

  

//Redis 全局 Redis

var RedisPool *RedisClient

  

//ConnectRedis 连接 redis 数据库,设置全局的 Redis 对象

func ConnectRedis() {

    config, err := ini.Load("./config/app.ini")

    if err != nil {

        //失败

        fmt.Printf("Fail to read file: %v", err)

        os.Exit(1)

    }

    address := config.Section("redis").Key("address").String()

    password := config.Section("redis").Key("password").String()

    db, _ := config.Section("redis").Key("db").Int()

    once.Do(func() {

        RedisPool = NewClient(address, password, db)

    })

    con_err := RedisPool.Ping()

    if con_err != nil {

        panic(con_err)

    }

}

  

// NewClient 创建一个新的 redis 连接

func NewClient(address string, password string, db int) *RedisClient {

    // 初始化自定的 RedisClient 实例

    rds := &RedisClient{}

    // 使用 redis 库里的 NewClient 初始化连接

    rds.Client = &redis.Pool{

        MaxIdle:     100,  //最大空闲

        MaxActive:   1000, //最大连接

        IdleTimeout: time.Duration(60) * time.Second,

        Wait:        true,

        Dial: func() (redis.Conn, error) {

            c, err := redis.Dial(

                "tcp",

                address,

                redis.DialPassword(password),

                redis.DialDatabase(int(db)),

                redis.DialConnectTimeout(time.Duration(60)*time.Second),

                redis.DialReadTimeout(time.Duration(60)*time.Second),

                redis.DialWriteTimeout(time.Duration(60)*time.Second),

            )

            if err != nil {

                return nil, err

            }

            return c, err

        },

    }

    return rds

}

  

// Ping 用以测试 redis 连接是否正常

func (rds *RedisClient) Ping() error {

    _, err := rds.Client.Get().Do("ping")

    return err

}

  

// Set 存储 key 对应的 value,且设置 expiration 过期时间(单位纳秒)

func (rds *RedisClient) Setex(key string, expiration int, value interface{}) bool {

    conn := rds.Client.Get()

    defer conn.Close()

    if _, err := conn.Do("setex", key, expiration, value); err != nil {

        fmt.Println(err)

        return false

    }

    return true

}

  

//

//Get 获取 key 对应的 value

func (rds *RedisClient) Get(key string) string {

    conn := rds.Client.Get()

    defer conn.Close()

    result, err := redis.String(conn.Do("Get", key))

    if err != nil {

        return ""

    }

    return result

}

  

//Get 获取 key 对应的 value

func (rds *RedisClient) Rpop(key string) (string, error) {

    conn := rds.Client.Get()

    defer conn.Close()

    result, err := redis.String(conn.Do("Rpop", key))

    if err != nil {

        return "", err

    }

    return result, nil

}

配置文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

app_name   = go-gin

  

  

[mysql]

ip       = 127.0.0.1

port     = 3306

user     = root

password = root

database = test

prefix   = tt_

#最大连接数

MaxIdleConns = 500

#最大空闲

MaxOpenConns = 50

  

[redis]

address   = 127.0.0.1:6379

password = 123456

db = 7

调用方法

1

2

3

4

5

6

7

8

9

func main() {

    dao.ConnectRedis()                 //初始化连接redis

    defer dao.RedisPool.Client.Close() //退出前执行关闭

    res, err := dao.RedisPool.Rpop("aaa")

    if err != nil {

        fmt.Println(err)

    }

    fmt.Println(res)

}

原文链接:
相关文章
最新更新