redis

package
v0.0.0-...-7429660 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2023 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

封装go语言redis client.

Background

此基础库库基于redigo进行封装。之所以封装一个原生的库,是因为便于维护,容易扩展其他的东西:

1. 支持stst统计上报

2. 以基础库的形式,使大家的代码保持统一

3. 基础库统一维护

4. 支持trace

Executing Commands

Redis client有一个通用的方法来执行redis命令:

Do(commandName string, args ...interface{}) (reply interface{}, err error)

Redis命令的参考(http://redis.io/commands) 列出了所有redis的命令, 一个使用Redis APPEND命令的例子:

n, err := r.Do("APPEND", "key", "value")

Configure

此配置适用于rpc-go基础库中用文件进行初始化基础库:

 [[redis]]
	server_name="queen-redis"
	addr="localhost:6379"
	password="password"
	max_idle=100
	max_active=100
	idle_timeout=1000
	connect_timeout=1000
	read_timeout=1000
	write_timeout=1000
	database=0
	retry=0

更通用的配置方法请参考RedisConfig类型

Trace

此redis client接入了公司内部的trace系统, 通过For函数进行接入:

ok, err := r.For(ctx).Set("key", "value")

更详细的内容请见For函数

Reply Helpers

Bool, Int, Bytes, String, Strings and Values 函数把Do的返回值转换成具体的类型。 这些函数的第二个参数是由Do函数返回error类型,日和error不是nil,那么这些helper 函数就直接返回这个错误,如果error是nil,那么函数把reply转换成特定的类型:

exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
    // handle error return from c.Do or type conversion error.
}

var value1 int
var value2 string
reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
if err != nil {
    // handle error
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrConnExhausted = errors.New("redis: connection exhausted, please retry")
	ErrTimeout       = errors.New("redis: i/o timeout, please retry")
)

Functions

func Bool

func Bool(reply interface{}, err error) (bool, error)

Bool 是一个helper函数,它把一个命令的reply转换成bool。如果err不是nil,Bool返回false,err。 否则Bool把reply按照下列方式转换成bool:

Reply type      Result
integer         value != 0, nil
bulk string     strconv.ParseBool(reply)
nil             false, ErrNil
other           false, error

func ByteSlices

func ByteSlices(reply interface{}, err error) ([][]byte, error)

ByteSlices is a helper that converts an array command reply to a [][]byte. If err is not equal to nil, then ByteSlices returns nil, err. Nil array items are stay nil. ByteSlices returns an error if an array item is not a bulk string or nil.

func Bytes

func Bytes(reply interface{}, err error) ([]byte, error)

func Float64

func Float64(reply interface{}, err error) (float64, error)

func Int

func Int(reply interface{}, err error) (int, error)

func Int64

func Int64(reply interface{}, err error) (int64, error)

func Int64Map

func Int64Map(result interface{}, err error) (map[string]int64, error)

func IntMap

func IntMap(result interface{}, err error) (map[string]int, error)

IntMap is a helper that converts an array of strings (alternating key, value) into a map[string]int. The HGETALL commands return replies in this format. Requires an even number of values in result.

func Ints

func Ints(reply interface{}, err error) ([]int, error)

func RedisPoolInit

func RedisPoolInit(config *RedisPoolConfig) *redis.Pool

过时的api, 请不要使用

func String

func String(reply interface{}, err error) (string, error)

String is a helper that converts a command reply to a string. If err is not equal to nil, then String returns "", err. Otherwise String converts the reply to a string as follows:

Reply type      Result
bulk string     string(reply), nil
simple string   reply, nil
nil             "",  ErrNil
other           "",  error

func StringMap

func StringMap(result interface{}, err error) (map[string]string, error)

StringMap is a helper that converts an array of strings (alternating key, value) into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format. Requires an even number of values in result.

func Strings

func Strings(reply interface{}, err error) ([]string, error)

Strings is a helper that converts an array command reply to a []string. If err is not equal to nil, then Strings returns nil, err. Nil array items are converted to "" in the output slice. Strings returns an error if an array item is not a bulk string or nil.

func Uint64

func Uint64(reply interface{}, err error) (uint64, error)

func Values

func Values(reply interface{}, err error) ([]interface{}, error)

Values is a helper that converts an array command reply to a []interface{}. If err is not equal to nil, then Values returns nil, err. Otherwise, Values converts the reply as follows:

Reply type      Result
array           reply, nil
nil             nil, ErrNil
other           nil, error

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

过时的api, 请不要使用

func NewCache

func NewCache(config *RedisPoolConfig) *Cache

过时的api, 请不要使用

func (*Cache) Get

func (c *Cache) Get(key string) ([]byte, error)

过时的api, 请不要使用

func (*Cache) MultiGet

func (c *Cache) MultiGet(ks ...string) ([][]byte, error)

过时的api, 请不要使用

func (*Cache) MultiSetWithExpire

func (c *Cache) MultiSetWithExpire(expire time.Duration, data ...string) error

过时的api, 请不要使用

func (*Cache) SetWithExpire

func (c *Cache) SetWithExpire(key, value string, expire time.Duration) error

过时的api, 请不要使用

type Manager

type Manager struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Manager 用于管理多个redis client, 通常在rpc-go基础库中使用

func NewManager

func NewManager(c []RedisConfig) (*Manager, error)

NewManager 初始化一个Manager

func (*Manager) Add

func (m *Manager) Add(name string, r *Redis)

func (*Manager) Get

func (m *Manager) Get(name string) *Redis

Get 使用RedisConfig结构体中的ServerName字段作为key来获取redis client

type Pipelining

type Pipelining struct {
	// contains filtered or unexported fields
}

Pipelining 提供了一些流水线的一些方法, 由NewPipelining函数创建

func (*Pipelining) Close

func (p *Pipelining) Close() error

func (*Pipelining) Flush

func (p *Pipelining) Flush() error

func (*Pipelining) Receive

func (p *Pipelining) Receive() (reply interface{}, err error)

func (*Pipelining) Send

func (p *Pipelining) Send(cmd string, args ...interface{}) error

type Redis

type Redis struct {
	// contains filtered or unexported fields
}

func NewRedis

func NewRedis(o *RedisConfig) (*Redis, error)

NewRedis 是redis客户端的初始化函数 初始化redis客户端有两种方式, 第一种方式是使用NewRedis函数进行初始化 第二种方式是使用rpc-go基础库通过配置文件进行初始化

func (Redis) Del

func (r Redis) Del(args ...interface{}) (count int, err error)

func (Redis) Do

func (r Redis) Do(cmd string, args ...interface{}) (reply interface{}, err error)

Do 函数为通用的函数, 可以执行任何redis服务器支持的命令

func (Redis) DoCtx

func (r Redis) DoCtx(ctx context.Context, cmd string, args ...interface{}) (interface{}, error)

DoCtx 函数与Do函数相比, 增加了一个context参数, 提供了超时的功能

func (Redis) Exists

func (r Redis) Exists(key string) (res bool, err error)

func (Redis) Expire

func (r Redis) Expire(key string, expire time.Duration) error

func (*Redis) For

func (r *Redis) For(ctx context.Context) *ctxRedis

For 会返回一个具有context的redis客户端, 这个函数 是为了支持redis客户端接入trace系统而提供的,参数ctx 通常是从基础库中传递下来的。

func (Redis) Get

func (r Redis) Get(key string) (ret []byte, err error)

func (Redis) GetInt

func (r Redis) GetInt(key string) (ret int, err error)

func (Redis) HDel

func (r Redis) HDel(key interface{}, fields ...interface{}) (res int, err error)

* hash

func (Redis) HGet

func (r Redis) HGet(key, field string) (res string, err error)

func (Redis) HGetAll

func (r Redis) HGetAll(key string) (res map[string]string, err error)

func (Redis) HGetInt

func (r Redis) HGetInt(key, field string) (res int, err error)

func (Redis) HIncrby

func (r Redis) HIncrby(key, field string, incr int) (res int64, err error)

func (Redis) HKeys

func (r Redis) HKeys(key string) (res []string, err error)

func (Redis) HMGet

func (r Redis) HMGet(key string, fields ...interface{}) (res []string, err error)

func (Redis) HMSet

func (r Redis) HMSet(key string, fields ...interface{}) (res string, err error)

func (Redis) HSet

func (r Redis) HSet(key, fieldk string, fieldv interface{}) (res int, err error)

func (Redis) Incrby

func (r Redis) Incrby(key string, incr int) (res int64, err error)

func (Redis) LLen

func (r Redis) LLen(key string) (res int64, err error)

func (Redis) LPush

func (r Redis) LPush(name string, fields ...interface{}) error

func (Redis) Lock

func (r Redis) Lock(key string, expire time.Duration) (uuid string, err error)

func (Redis) MGet

func (r Redis) MGet(keys ...interface{}) (ret [][]byte, err error)

func (Redis) MSet

func (r Redis) MSet(keys ...interface{}) (ret string, err error)

func (*Redis) NewPipelining

func (r *Redis) NewPipelining(ctx context.Context) (*Pipelining, error)

NewPipelining函数创建一个Pipelining, 参数ctx用于trace系统

func (Redis) RPop

func (r Redis) RPop(key string) (res string, err error)

func (Redis) Receive

func (r Redis) Receive(name string, closech chan struct{}, bufferSize int) chan []byte

func (Redis) ReceiveBlock

func (r Redis) ReceiveBlock(name string, closech chan struct{}, bufferSize int, block int) chan []byte

func (Redis) SAdd

func (r Redis) SAdd(key string, members ...interface{}) (res int, err error)

* set

func (Redis) SIsMember

func (r Redis) SIsMember(key string, member string) (res bool, err error)

func (Redis) SMembers

func (r Redis) SMembers(key string) (res []string, err error)

func (Redis) SRem

func (r Redis) SRem(key string, members ...interface{}) (res int, err error)

func (Redis) Send

func (r Redis) Send(name string, fields ...interface{}) error

func (Redis) Set

func (r Redis) Set(key, value interface{}) (ret bool, err error)

Set 返回两个参数,err不为空为服务器内服错误, 当命令执行成功时,ret为true 使用这个函数时需要同时判断这两个返回值

func (Redis) SetExSecond

func (r Redis) SetExSecond(key, value interface{}, dur int) (ret string, err error)

func (Redis) Subscribe

func (r Redis) Subscribe(ctx context.Context, key string, maxSize int) (chan []byte, error)

func (Redis) TryLock

func (r Redis) TryLock(key string, acquireTimeout, expireTimeout time.Duration) (uuid string, err error)

func (Redis) Unlock

func (r Redis) Unlock(key string, uuid string) (err error)

func (Redis) ZAdd

func (r Redis) ZAdd(key string, args ...interface{}) (res int, err error)

func (Redis) ZCard

func (r Redis) ZCard(key string) (res int, err error)

func (Redis) ZCount

func (r Redis) ZCount(key string, min, max int) (res int, err error)

func (Redis) ZIncrby

func (r Redis) ZIncrby(key string, incr int, member string) (res int, err error)

func (Redis) ZRange

func (r Redis) ZRange(key string, args ...interface{}) (res []string, err error)

func (Redis) ZRangeInt

func (r Redis) ZRangeInt(key string, start, stop int) (res []int, err error)

func (Redis) ZRangeWithScore

func (r Redis) ZRangeWithScore(key string, start, stop int) (res []string, err error)

func (Redis) ZRank

func (r Redis) ZRank(key string, member string) (res int, err error)

* If the member not in the zset or key not exits, ZRank will return ErrNil

func (Redis) ZRem

func (r Redis) ZRem(key string, members ...interface{}) (res int, err error)

* If the members not in the zset or key not exits, ZRem will return ErrNil

func (Redis) ZRemrangebyrank

func (r Redis) ZRemrangebyrank(key string, members ...interface{}) (res int, err error)

func (Redis) ZRevRangeWithScore

func (r Redis) ZRevRangeWithScore(key string, start, stop int) (res []string, err error)

func (Redis) ZScore

func (r Redis) ZScore(key, member string) (res float64, err error)

* If the member not in the zset or key not exits, ZScore will return ErrNil

func (Redis) Zrevrange

func (r Redis) Zrevrange(key string, args ...interface{}) (res []string, err error)

func (Redis) Zrevrangebyscore

func (r Redis) Zrevrangebyscore(key string, args ...interface{}) (res []string, err error)

func (Redis) ZrevrangebyscoreInt

func (r Redis) ZrevrangebyscoreInt(key string, args ...interface{}) (res []int, err error)

type RedisConfig

type RedisConfig struct {
	// 这个字段会上报到stats和trace系统
	ServerName string `json:"server_name"`

	// Redis服务器的host和port "localhost:6379"
	Addr string `json:"addr"`

	// 连接到redis服务器的密码
	Password string `json:"password"`

	// 在连接池中可以存在的最大空闲连接数
	MaxIdle int `json:"max_idle"`

	// Maximum number of connections allocated by the pool at a given time.
	// When zero, there is no limit on the number of connections in the pool.
	MaxActive int `json:"max_active"`

	// Close connections after remaining idle for this duration. If the value
	// is zero, then idle connections are not closed. Applications should set
	// the timeout to a value less than the server's timeout.
	IdleTimeout int `json:"idle_timeout"`

	// Specifies the timeout for connecting to the Redis server.
	ConnectTimeout int `json:"connect_timeout"`
	ReadTimeout    int `json:"read_timeout"`

	// WriteTimeout specifies the timeout for writing a single command.
	WriteTimeout int `json:"write_timeout"`

	// Database specifies the database to select when dialing a connection.
	Database int `json:"database"`

	// 慢日志打印, 单位毫秒, 如果一个请求的时间慢于这个值,
	// 将会把详细信息打印在slow.log日志中
	SlowTime int `json:"slow_time"`

	// 内部重试次数
	Retry int `json:"retry"`
}

RedisConfig结构体作为NewRedis函数的参数,用于初始化Redis结构体。

type RedisPoolConfig

type RedisPoolConfig struct {
	Addr           string `json:"addr"`
	Password       string `json:"password"`
	MaxIdle        int    `json:"max_idle"`
	IdleTimeout    int    `json:"idle_timeout"`
	MaxActive      int    `json:"max_active"`
	ConnectTimeout int    `json:"connect_timeout"`
	ReadTimeout    int    `json:"read_timeout"`
	WriteTimeout   int    `json:"write_timeout"`
	Database       int    `json:"database"`
}

过时的api, 请不要使用

Directories

Path Synopsis
这个package已经过时了, 新代码请不要使用这个package里面得任何api和type
这个package已经过时了, 新代码请不要使用这个package里面得任何api和type

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL