go redis pool
Redis
https://redis.io/
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
Why Redis
- 高性能
- 支持丰富的数据类型
- 操作原子性
- 支持很多的特性
Redis 连接
name | comment |
---|---|
host | redis 服务所在的 服务器 |
port | redis 服务的端口号, 默认为 6379 |
auth | redis 密码,默认为空 |
db | 要使用的 redis db 序列号 |
go 连接 redis
使用库
"github.com/gogf/gf/third/github.com/gomodule/redigo/redis"
连接
package main
import (
"fmt"
"github.com/gogf/gf/third/github.com/gomodule/redigo/redis"
)
func main() {
var (
conn redis.Conn
err error
)
// 使用 Dial 连接 tcp
if conn, err = redis.Dial("tcp", "tcloud-api.tsbx.com:6379"); err != nil {
fmt.Println(err.Error())
}
// 退出时 close
defer conn.Close()
// 使用 密码 访问
if _, err := conn.Do("AUTH", "tcloud"); err != nil {
conn.Close()
}
// 选择要使用的数据库
if _, err := conn.Do("SELECT", "1"); err != nil {
}
}
redis 操作
set key - value
if _, err := conn.Do("Set", "key", "value", "EX", "5"); err != nil {
fmt.Println(err.Error())
}
get value by key
var (
value string
err error
)
if value, err = redis.String(conn.Do("Get", "key")); err != nil {
fmt.Println(err.Error())
}
fmt.Println(value)
key exists check
var (
exists bool
err error
)
if exists, err = redis.Bool(conn.Do("EXISTS", "key")); err != nil {
fmt.Println(err.Error())
}
fmt.Println(exists)
使用 redis pool
package utils
import (
"fmt"
"github.com/gogf/gf/third/github.com/gomodule/redigo/redis"
)
var (
RedisPool *redis.Pool // redis pool
)
// 初始化 pool
func InitRedisPool(network string, host string, password string, database int) (pool *redis.Pool) {
pool = &redis.Pool{
MaxIdle: 16,
MaxActive: 0,
IdleTimeout: 300,
Dial: func() (redis.Conn, error) {
conn, err := redis.Dial(network, host)
fmt.Println(conn, err)
if err != nil {
return nil, err
}
if _, err := conn.Do("AUTH", password); err != nil {
conn.Close()
return nil, err
}
if _, err := conn.Do("SELECT", database); err != nil {
return nil, err
}
return conn, nil
},
}
RedisPool = pool
return
}
func RedisSet(redisConn redis.Conn, key string, value string) (code int, err error) {
if _, err := redisConn.Do("Set", key, value); err != nil {
code = 102
}
return
}
func RedisGet(redisConn redis.Conn, key string) (value string, err error) {
fmt.Println(key)
if value, err = redis.String(redisConn.Do("Get", key)); err != nil {
value = "0"
}
return
}
使用 pool 进行获取
package test
import (
"redis-test/util"
)
func Test(){
utils.InitRedisPool("tcp", "tcloud-api.tsbx.com:6379", "tcloud", 1)
conn := utils.RedisPool.Get()
defer conn.Close()
if code, err := utils.RedisSet(conn, "key", "value"); err != nil {
fmt.Println(err.Error())
}
}