目录
- Golang使用Redis与连接池
- redis数据源连接池
- Golang Redis连接池封装
- 创建连接池方法文件
- 配置文件
- 调用方法
- 总结
Golang使用Redis与连接池
使用下载go的redis包go get github.com/gomodule/redigo/redis 如果网不好的话就很费劲了
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数据源连接池
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连接池封装
创建连接池方法文件
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
}
配置文件
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
调用方法
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)
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)