golang 初始化Redis的连接池
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 初始化Redis的连接池相关的知识,希望对你有一定的参考价值。
golang总结-Redis整合
go get github.com/gomodule/redigo/redis
1. 基本用法
- 获取连接
package conn
import (
"github.com/gomodule/redigo/redis"
"log"
)
const (
redis_passwd = ""
redis_host = ""
redis_port = ""
redis_address = "192.168.2.130:6379"
)
func getConn() redis.Conn {
conn, err := redis.Dial("tcp", redis_address)
if err != nil {
log.Println("redis connect err", err)
panic(err)
}
return conn
}
- 操作redis
package conn
import (
"fmt"
"github.com/gomodule/redigo/redis"
"log"
)
var c = getConn()
//string 操作
func Set(key string, value interface{}) bool {
defer c.Close()
_, err := c.Do("set", key, value)
if err != nil {
log.Println("set a value error,", err)
return false
}
return true
}
func Get(key string) string {
defer c.Close()
value, err := redis.String(c.Do("get", key))
if err != nil {
log.Println("get a value error,", err)
return ""
}
return value
}
func Del(key string) bool {
defer c.Close()
_, err := c.Do("del", key)
if err != nil {
log.Println("del a key error, ", err)
return false
}
return true
}
//Hash操作
func HashSet(key string, data map[string]interface{}) {
defer c.Close()
for k, v := range data {
_, err := c.Do("hset", key, k, v)
if err != nil {
log.Println("hset a error, ", err)
continue
}
}
}
func HashMGet(key string) map[string]interface{} {
defer c.Close()
data := make(map[string]interface{})
reply, err := redis.ByteSlices(c.Do("hgetall", key))
if err != nil {
log.Println("hmget error, ", err)
return nil
}
for i, v := range reply {
fmt.Println(string(v))
if i % 2 == 0 {
data[string(v)] = string(reply[i+1])
}
continue
}
return data
}
2. Redis连接池
package pool
import (
"github.com/gomodule/redigo/redis"
"time"
)
var (
pool *redis.Pool
)
const (
redis_host = "192.168.2.130:6379"
)
func init() {
pool = &redis.Pool{
MaxIdle: 10,
MaxActive: 0, //0表示没有限制
IdleTimeout: 1 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", redis_host)
},
}
}
获取连接:conn := pool.Get()
以上是关于golang 初始化Redis的连接池的主要内容,如果未能解决你的问题,请参考以下文章