Golang使用Redis與連接池方式
更新時間:2024年06月01日 11:16:28 作者:T
這篇文章主要介紹了Golang使用Redis與連接池方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Golang使用Redis與連接池
使用下載go的redis包go get github.com/gomodule/redigo/redis 如果網(wǎng)不好的話就很費勁了
package main
import (
"fmt"
"github.com/gomodule/redigo/redis" // 引入redis包
)
func main() {
//連接數(shù)據(jù)源
rediss, err := redis.Dial("tcp", "127.0.01:6379")
if err != nil {
fmt.Println("連接異常", err)
}
//插入string數(shù)據(jù)
test, err := rediss.Do("set", "test", "hi")
if err != nil {
fmt.Println("插入數(shù)據(jù)失敗", err)
}
fmt.Println(test)
//讀取string數(shù)據(jù)
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)
//設(shè)置key 過期時間
rediss.Do("expire", "hh", 1)
//關(guān)閉redis
rediss.Close()
}
redis數(shù)據(jù)源連接池
package main
import (
"fmt"
"github.com/gomodule/redigo/redis" // 引入redis包
)
var pool *redis.Pool
func init() {
pool = &redis.Pool{
MaxIdle: 8, //最大空閑連接數(shù)
MaxActive: 0, //表示和數(shù)據(jù)庫最大連接數(shù)。0表示沒有限制
IdleTimeout: 100, //最大空閑時間
Dial: func() (redis.Conn, error) { //初始化連接 redis 地址
return redis.Dial("tcp", "127.0.01:6379")
},
}
}
func main() {
//獲取連接
conn := pool.Get()
//插入數(shù)據(jù)
do, err := conn.Do("set", "11", "11")
if err != nil {
fmt.Println("插入失敗", err)
}
fmt.Println(do)
//關(guān)閉redis
conn.Close()
}Golang Redis連接池封裝
創(chuàng)建連接池方法文件
package dao
import (
"fmt"
"github.com/gomodule/redigo/redis"
"gopkg.in/ini.v1"
"os"
"sync"
"time"
)
var once sync.Once
// RedisClient Redis 服務(wù)
type RedisClient struct {
Client *redis.Pool
}
//Redis 全局 Redis
var RedisPool *RedisClient
//ConnectRedis 連接 redis 數(shù)據(jù)庫,設(shè)置全局的 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 創(chuàng)建一個新的 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 對應(yīng)的 value,且設(shè)置 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 對應(yīng)的 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 對應(yīng)的 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_ #最大連接數(shù) MaxIdleConns = 500 #最大空閑 MaxOpenConns = 50 [redis] address = 127.0.0.1:6379 password = 123456 db = 7
調(diào)用方法
func main() {
dao.ConnectRedis() //初始化連接redis
defer dao.RedisPool.Client.Close() //退出前執(zhí)行關(guān)閉
res, err := dao.RedisPool.Rpop("aaa")
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Golang空結(jié)構(gòu)體struct{}用途,你知道嗎
這篇文章主要介紹了Golang空結(jié)構(gòu)體struct{}用途,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Go語言通過chan進行數(shù)據(jù)傳遞的方法詳解
這篇文章主要為大家詳細介紹了Go語言如何通過chan進行數(shù)據(jù)傳遞的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2023-06-06
Go語言構(gòu)建流數(shù)據(jù)pipeline的示例詳解
Go的并發(fā)原語可以輕松構(gòu)建流數(shù)據(jù)管道,從而高效利用?I/O?和多個?CPU,?本文展示了此類pipelines的示例,強調(diào)了操作失敗時出現(xiàn)的細微之處,并介紹了干凈地處理失敗的技術(shù),希望對大家有所幫助2024-02-02

