gedis

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2023 License: MIT Imports: 16 Imported by: 0

README

Redis

redis 4 golang base on redigo

1. use pool
package main

import (
	"log"
	"time"

	"github.com/grpc-boot/gedis"
)

func main() {
	option := gedis.Option{
		Host:            "127.0.0.1",
		Port:            6379,
		Auth:            "",
		Db:              0,
		MaxConnLifetime: 600,  //单位秒
		MaxIdle:         10,
		MaxActive:       20,
		ReadTimeout:     300, //单位毫秒
		WriteTimeout:    0, //单位毫秒
	}

	pool := gedis.NewPool(option)
	var key = `gedis`

	ok, err := pool.Set(key, time.Now().Unix())
	if err != nil {
		log.Fatalf("set err:%s\n", err.Error())
	}

	if !ok {
		log.Printf("set failed\n")
	}

	val, _ := pool.Get(key)
	log.Printf("get val:%s\n", val)
}
2. use group
package main

import (
	"log"
	"math/rand"

	"github.com/grpc-boot/gedis"
)

func main() {
	options := []gedis.GroupOption{
			{
				Option: gedis.Option{
					Host:            "127.0.0.1",
					Port:            6379,
					Auth:            "",
					Db:              0,
					MaxConnLifetime: 600, //单位秒
					MaxIdle:         10,
					MaxActive:       20,
					ReadTimeout:     300, //单位毫秒
					WriteTimeout:    0,   //单位毫秒
				},
				VirtualCount: 32,  //虚拟节点数量
			},
	}

	group, err := gedis.NewGroup(options...)
	if err != nil {
		log.Printf("init redis group err:%s", err)
	}

	var (
		userId = `123456`
		key    = `user:`+ userId
	)

	pool, err := group.Get(userId)
	if err != nil {
		log.Printf("get pool err:%s", err)
	}


	ok, err := pool.HMSet(key, "name", "user1", "age", rand.Int31())
	if err != nil {
		log.Printf("get pool err:%s", err)
	}

	if !ok {
		log.Printf("hmset failed\n")
	}

	kv, err := pool.HGetAll(key)
	if err != nil {
		log.Printf("get pool err:%s", err)
	}
	log.Printf("userinfo:%+v\n", kv)
}
3. pub/sub

app.yml

host: '127.0.0.1'
port: 6379
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/grpc-boot/gedis"

	"github.com/grpc-boot/base"
)

var (
	subConn gedis.SubConn
	option  gedis.Option
)

func init() {
	err := base.YamlDecodeFile("./app.yml", &option)
	if err != nil {
		base.RedFatal("load config err:%s", err.Error())
	}

	subConn, err = gedis.NewSubConn(option)
	if err != nil {
		base.RedFatal("new sub conn err:%s", err.Error())
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		<-time.After(time.Second * 10)
		cancel()
	}()

	sub(ctx)
	publish()
}

func sub(ctx context.Context) {
	ch, err := subConn.PSubscribeChannel(ctx, 1024, `chan*`)
	if err != nil {
		base.RedFatal("subscribe err:%s", err.Error())
	}

	for w := 0; w < 8; w++ {
		go func() {
			for {
				msg, isOpen := <-ch
				if !isOpen {
					return
				}

				switch m := msg.(type) {
				case gedis.Msg:
					base.Green("receive pattern:%s channel:%s, msg:%s", m.Pattern, m.Channel, string(m.Data))
				case error:
					base.Red("receive err:%s", m.Error())
				case gedis.Pong:
					continue
				}

			}
		}()
	}
}

func publish() {
	var (
		tick   = time.NewTicker(time.Second)
		num    = 0
		recNum int
		err    error
	)

	for range tick.C {
		num++

		ch, msg := fmt.Sprintf("chan%d", num%2+1), fmt.Sprintf(`{"id":%d, "cmd":"chat", "data":{}}`, num)
		p := gedis.NewPool(option)
		recNum, err = p.Publish(ch, msg)
		if err != nil {
			base.Red("publish err:%s", err.Error())
			continue
		}
		base.Green("publish recNum:%d, ch:%s, msg:%s", recNum, ch, msg)
	}
}
4. lock
package main

import (
	"log"

	"github.com/grpc-boot/gedis"
)

func main() {
	option := gedis.Option{
		Host:            "127.0.0.1",
		Port:            6379,
		Auth:            "",
		Db:              0,
		MaxConnLifetime: 600, //单位秒
		MaxIdle:         10,
		MaxActive:       20,
		ReadTimeout:     300, //单位毫秒
		WriteTimeout:    0,   //单位毫秒
	}

	pl := gedis.NewPool(option)
	var key = `t_lock`

	token, err := pl.Acquire(key, 3)
	if err != nil {
		log.Fatalf("get lock err:%s", err.Error())
	}

	if token == 0 {
		log.Println("未获得锁")
		log.Println("逻辑处理")
		return
	}

	//释放锁
	defer pl.Release(key, token)

	log.Println("获得锁")
	log.Println("正常逻辑")
}
5. cache
package main

import (
	"log"
	"time"

	"github.com/grpc-boot/gedis"
)

func main() {
	option := gedis.Option{
		Host:                  "127.0.0.1",
		Port:                  6379,
		Auth:                  "",
		Db:                    0,
		MaxConnLifetimeSecond: 600, //单位秒
		MaxIdle:               10,
		MaxActive:             20,
		ReadTimeout:           300, //单位毫秒
		WriteTimeout:          0,   //单位毫秒
	}

	pl := gedis.NewPool(option)
	var (
		key     = `t_cache`
		current = time.Now().Unix()
	)

	value, err := pl.CacheGet(key, current, 6, func() (value []byte, err error) {
		//模拟耗时
		time.Sleep(1)
		return []byte(time.Now().String()), nil
	})

	if err != nil {
		log.Fatalf("get cache err:%s", err.Error())
	}

	log.Printf("%s\n", value)

	value, err = pl.LevelCache(&gedis.DefaultLocalCache, key, current, 6, func() (value []byte, err error) {
		//模拟耗时
		time.Sleep(1)
		return []byte(time.Now().String()), nil
	})

	if err != nil {
		log.Fatalf("get cache err:%s", err.Error())
	}

	log.Printf("%s\n", value)
}
6. limit
package main

import (
	"log"
	"sync"

	"github.com/grpc-boot/gedis"
)

func main() {
	option := gedis.Option{
		Host:            "127.0.0.1",
		Port:            6379,
		Auth:            "",
		Db:              0,
		MaxConnLifetime: 600, //单位秒
		MaxIdle:         10,
		MaxActive:       20,
		ReadTimeout:     300, //单位毫秒
		WriteTimeout:    0,   //单位毫秒
	}

	pl := gedis.NewPool(option)
	var key = `t_limit:127.0.0.1`
	var wa sync.WaitGroup
	wa.Add(1)

	//令牌桶限速,每秒3个请求
	work(4, func() {
		ok, err := pl.SecondLimitByToken(key, 3, 1)
		if err != nil {
			log.Fatal(err)
		}
		if ok {
			log.Println("ok")
		}
	})

	//自然时间限速,每秒3个请求
	/*work(8, func() {
		ok, err := pl.SecondLimitByTime(key, 3, 1)
		if err != nil {
			log.Fatal(err)
		}
		if ok {
			log.Println("ok")
		}
	})*/

	//自然时间限速,每分钟3个请求
	/*work(8, func() {
		ok, err := pl.MinuteLimitByTime(key, 3, 1)
		if err != nil {
			log.Fatal(err)
		}
		if ok {
			log.Println("ok")
		}
	})*/

	wa.Wait()
}

func work(num int, hand func()) {
	for i:=0; i<num; i++ {
		go func() {
			for {
				hand()
			}
		}()
	}
}

Documentation

Index

Constants

View Source
const (
	Transaction = 1
	Pipeline    = 2
)
View Source
const (
	Ok      = `OK`
	Success = 1
)
View Source
const (
	DefaultNotifyPattern = `KA$`
)

Variables

View Source
var (
	ErrKeyFormat = NewError(`key format error`)
	ErrKeyList   = NewError(`key list is empty`)
)
View Source
var (
	Error = base.Error
	Debug = base.Debug
)
View Source
var (
	PipeMulti = func() Multi {
		m := multiPool.Get().(*multi)
		m.kind = Pipeline
		return m
	}

	TransMulti = func() Multi {
		m := multiPool.Get().(*multi)
		m.kind = Transaction
		return m
	}

	ReleaseMulti = func(m Multi) {
		m.Reset()
		multiPool.Put(m)
	}
)
View Source
var DefaultLocalCache sync.Map
View Source
var (
	ErrOptionEmpty = errors.New(`redis option empty`)
)
View Source
var (
	ErrUnKnownSubMsg = errors.New(`unknown pubsub notification`)
)

Functions

func BytesMap added in v1.0.2

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

func Get added in v1.0.3

func Get(key string) (value interface{})

func NewError added in v1.0.6

func NewError(msg string) error

func Range added in v1.0.3

func Range(handler func(key string, pool Pool, group Group) bool)

func Set added in v1.0.3

func Set(key string, value interface{})

func SetGroup added in v1.0.3

func SetGroup(key string, options ...GroupOption) (err error)

func SetPool added in v1.0.3

func SetPool(key string, option Option)

func SetPoolByJson added in v1.0.3

func SetPoolByJson(key string, jsonStr string) (err error)

func String

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

String 转换为String

Types

type Cmd

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

type Conf added in v1.0.6

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

func NewConf added in v1.0.6

func NewConf(option ConfOption) (c *Conf, err error)

func (*Conf) Get added in v1.0.6

func (c *Conf) Get(key string) base.JsonParam

func (*Conf) Range added in v1.0.6

func (c *Conf) Range(f func(key string, value base.JsonParam) bool)

func (*Conf) SetKeyspaceNotify added in v1.0.6

func (c *Conf) SetKeyspaceNotify(pattern string) error

type ConfOption added in v1.0.6

type ConfOption struct {
	Option             Option   `json:"option" yaml:"option"`
	Prefix             string   `json:"prefix" yaml:"prefix"`
	KeyList            []string `json:"key_list" yaml:"key_list"`
	SyncIntervalSecond int64    `json:"sync_interval_second" yaml:"sync_interval_second"`
	SyncPageSize       int      `json:"sync_page_size" yaml:"sync_page_size"`
}

type GedisError added in v1.0.6

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

func (*GedisError) Error added in v1.0.6

func (ge *GedisError) Error() string

func (*GedisError) Is added in v1.0.6

func (ge *GedisError) Is(target error) bool

type Group

type Group interface {
	Get(key interface{}) (p Pool, err error)
	Index(index int) (p Pool, err error)
	Range(handler func(index int, p Pool, hitCount uint64) (handled bool))
}

func GetGroup added in v1.0.3

func GetGroup(key string) Group

func NewGroup

func NewGroup(options ...GroupOption) (g Group, err error)

NewGroup 实例化Group

type GroupOption

type GroupOption struct {
	Option       Option `yaml:"option" json:"option"`
	VirtualCount int    `yaml:"virtualCount" json:"virtualCount"`
}

type Handler added in v1.0.2

type Handler func() (value []byte, err error)

type Item

type Item struct {
	CreatedAt    int64  `json:"created_at"`
	UpdatedAt    int64  `json:"updated_at"`
	UpdatedCount int64  `json:"updated_count"`
	Value        []byte `json:"value"`
}

Item 缓存Item

func (*Item) Hit

func (i *Item) Hit(timeoutSecond int64, current int64) bool

type Location

type Location struct {
	Member   string
	Distance string
	Hash     int64
	Lng      float64
	Lat      float64
}

Location 位置

func Locations

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

Locations 转换为Location信息

type Log added in v1.0.2

type Log func(msg string, fields ...zap.Field)

type Msg

type Msg struct {
	Pattern string
	Channel string
	Data    []byte
}

type Multi

type Multi interface {
	//-----------------Key--------------------------
	Del(keys ...interface{}) Multi
	Exists(key interface{}) Multi
	Expire(key interface{}, second int64) Multi
	ExpireAt(key interface{}, unixTime int64) Multi
	Ttl(key interface{}) Multi
	Persist(key interface{}) Multi
	Keys(pattern string) Multi
	Dump(key string) Multi
	Restore(key string, pttl int64, serializedValue string) Multi
	Move(key string, db int) Multi
	RandomKey() Multi
	ReName(key string, newKey string) Multi
	ReNameNx(key string, newKey string) Multi
	Type(key string) Multi

	//-----------------String--------------------------
	Append(key string, value interface{}) Multi
	Get(key string) Multi
	MGet(keys ...string) Multi
	MSet(key1 string, value1 interface{}, keyValues ...interface{}) Multi
	MSetByMap(keyValues map[string]interface{}) Multi
	Set(key string, value interface{}, args ...interface{}) Multi
	SetEx(key string, seconds int, value interface{}) Multi
	SetNx(key string, value interface{}) Multi
	GetSet(key string, value interface{}) Multi
	Incr(key string) Multi
	Decr(key string) Multi
	IncrBy(key string, increment int) Multi
	DecrBy(key string, decrement int) Multi
	IncrByFloat(key string, increment float64) Multi
	SetRange(key string, offset int, val string) Multi
	GetRange(key string, start, end int) Multi
	SetBit(key string, offset int, bit int8) Multi
	GetBit(key string, offset int) Multi
	BitCount(key string, args ...interface{}) Multi

	//-----------------Hash--------------------------
	HSet(key string, field string, value interface{}) Multi
	HSetNx(key string, field string, value interface{}) Multi
	HGet(key string, field string) Multi
	HMSet(key string, field1 string, value1 interface{}, args ...interface{}) Multi
	HMSetMap(key string, keyValues map[string]interface{}) Multi
	HMGet(key string, fields ...string) Multi
	HGetAll(key string) Multi
	HDel(key string, fields ...string) Multi
	HExists(key string, field string) Multi
	HIncrBy(key string, field string, increment int) Multi
	HIncrByFloat(key string, field string, increment float64) Multi
	HKeys(key string) Multi
	HVals(key string) Multi
	HLen(key string) Multi

	//-----------------List--------------------------
	LLen(key string) Multi
	LPush(key string, values ...interface{}) Multi
	LPushX(key string, value interface{}) Multi
	LPop(key string) Multi
	LIndex(key string, index int) Multi
	LRange(key string, start, stop int) Multi
	LSet(key string, index int, value interface{}) Multi
	LTrim(key string, start, stop int) Multi
	RPush(key string, values ...interface{}) Multi
	RPushX(key string, value interface{}) Multi
	RPop(key string) Multi

	//--------------------Set---------------------------
	SAdd(key string, members ...interface{}) Multi
	SMembers(key string) Multi
	SIsMember(key string, member interface{}) Multi
	SCard(key string) Multi
	SPop(key string) Multi
	SRandMember(key string, count int) Multi
	SRem(key string, members ...interface{}) Multi
	SMove(sourceSetKey, destinationSetKey string, member interface{}) Multi
	SDiff(keys ...interface{}) Multi
	SDiffStore(destinationSetKey string, keys ...string) Multi
	SInter(keys ...interface{}) Multi
	SInterStore(destinationSetKey string, keys ...string) Multi
	SUnion(keys ...interface{}) Multi
	SUnionStore(destinationSetKey string, keys ...string) Multi

	//--------------------ZSet---------------------------
	ZAdd(key string, score, value interface{}, scoreAndValues ...interface{}) Multi
	ZAddMap(key string, membersMap map[string]interface{}) Multi
	ZCard(key string) Multi
	ZCount(key string, minScore, maxScore interface{}) Multi
	ZIncrBy(key string, increment interface{}, member string) Multi
	ZRange(key string, startIndex, stopIndex int) Multi
	ZRevRange(key string, startIndex, stopIndex int) Multi
	ZRangeWithScore(key string, startIndex, stopIndex int) Multi
	ZRevRangeWithScore(key string, startIndex, stopIndex int) Multi
	ZRangeByScore(key string, minScore, maxScore interface{}, offset, limit int) Multi
	ZRevRangeByScore(key string, maxScore, minScore interface{}, offset, limit int) Multi
	ZRangeByScoreWithScore(key string, minScore, maxScore interface{}, offset, limit int) Multi
	ZRevRangeByScoreWithScore(key string, maxScore, minScore interface{}, offset, limit int) Multi
	ZRank(key, member string) Multi
	ZRevRank(key, member string) Multi
	ZScore(key, member string) Multi
	ZRem(key string, members ...interface{}) Multi
	ZRemRangeByRank(key string, startIndex, stopIndex int) Multi

	//--------------------ZSet---------------------------
	GeoAdd(key string, longitude, latitude float64, member interface{}, args ...interface{}) Multi
	GeoHash(key string, members ...interface{}) Multi
	GeoDel(key string, members ...interface{}) Multi
	GeoDist(key string, member1, member2 interface{}, unit string) Multi
	GeoPos(key string, members ...interface{}) Multi
	GeoRadius(key string, longitude, latitude float64, radius interface{}, unit string, count int, sort string) Multi
	GeoRadiusByMember(key string, member interface{}, radius interface{}, unit string, count int, sort string) Multi

	Reset()
	Kind() uint8
	CmdList() []Cmd
}

type Option

type Option struct {
	Host                  string `yaml:"host" json:"host"`
	Port                  int    `yaml:"port" json:"port"`
	Auth                  string `yaml:"auth" json:"auth"`
	Db                    uint8  `yaml:"db" json:"db"`
	MaxConnLifetimeSecond int    `yaml:"maxConnLifetimeSecond" json:"maxConnLifetimeSecond"`
	IdleTimeoutSecond     int    `yaml:"idleTimeoutSecond" json:"idleTimeoutSecond"`
	MaxIdle               int    `yaml:"maxIdle" json:"maxIdle"`
	MaxActive             int    `yaml:"maxActive" json:"maxActive"`
	Wait                  bool   `yaml:"wait" json:"wait"`
	//单位ms
	ConnectTimeout int `yaml:"connectTimeout" json:"connectTimeout"`
	//单位ms
	ReadTimeout int `yaml:"readTimeout" json:"readTimeout"`
	//单位ms
	WriteTimeout int `yaml:"writeTimeout" json:"writeTimeout"`
	//节点索引
	Index int `yaml:"index" json:"index"`
}

func DefaultOption added in v1.0.3

func DefaultOption() Option

type Pong

type Pong struct {
	Data string
}

type Pool

type Pool interface {
	base.CanHash

	ActiveCount() (num int)
	IdleCount() (num int)
	Stats() redigo.PoolStats
	Close() (err error)

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

	//-----------------Key--------------------------
	Del(keys ...interface{}) (delNum int, err error)
	Exists(key interface{}) (exists bool, err error)
	Expire(key interface{}, second int64) (success int, err error)
	ExpireAt(key interface{}, unixTime int64) (success int, err error)
	Ttl(key interface{}) (second int64, err error)
	Persist(key interface{}) (success int, err error)
	Scan(cursor int, match string, count int) (newCursor int, keys []string, err error)
	Keys(pattern string) (keys []string, err error)
	Dump(key string) (serializedValue string, err error)
	Restore(key string, pttl int64, serializedValue string) (ok bool, err error)
	Move(key string, db int) (success int, err error)
	RandomKey() (key string, err error)
	ReName(key string, newKey string) (ok bool, err error)
	ReNameNx(key string, newKey string) (success int, err error)
	Type(key string) (t string, err error)

	//-----------------String--------------------------
	Append(key string, value interface{}) (strLength int, err error)
	Get(key string) (val string, err error)
	GetBytes(key string) (val []byte, err error)
	MGet(keys ...string) (values []string, err error)
	MGetMap(keys ...string) (keyValue map[string]string, err error)
	MGetBytesMap(keys ...string) (keyValue map[string][]byte, err error)
	MSet(key1 string, value1 interface{}, keyValues ...interface{}) (ok bool, err error)
	MSetByMap(keyValues map[string]interface{}) (ok bool, err error)
	Set(key string, value interface{}, args ...interface{}) (ok bool, err error)
	SetEx(key string, seconds int, value interface{}) (ok bool, err error)
	SetNx(key string, value interface{}) (ok int, err error)
	GetSet(key string, value interface{}) (oldValue string, err error)
	Incr(key string) (val int64, err error)
	Decr(key string) (val int64, err error)
	IncrBy(key string, increment int) (val int64, err error)
	DecrBy(key string, decrement int) (val int64, err error)
	IncrByFloat(key string, increment float64) (val float64, err error)
	SetRange(key string, offset int, val string) (strLength int, err error)
	GetRange(key string, start, end int) (val string, err error)
	SetBit(key string, offset int, bit int8) (oldBit int, err error)
	GetBit(key string, offset int) (bit int, err error)
	BitCount(key string, args ...interface{}) (num int, err error)

	//-----------------Hash--------------------------
	HSet(key string, field string, value interface{}) (isNew int, err error)
	HSetNx(key string, field string, value interface{}) (ok int, err error)
	HGet(key string, field string) (value string, err error)
	HMSet(key string, field1 string, value1 interface{}, args ...interface{}) (ok bool, err error)
	HMSetMap(key string, keyValues map[string]interface{}) (ok bool, err error)
	HMGet(key string, fields ...string) (values []string, err error)
	HMGetMap(key string, fields ...string) (keyValues map[string]string, err error)
	HGetAll(key string) (keyValues map[string]string, err error)
	HGetAllBytes(key string) (keyValues map[string][]byte, err error)
	HDel(key string, fields ...string) (delNum int, err error)
	HExists(key string, field string) (exists bool, err error)
	HIncrBy(key string, field string, increment int) (val int64, err error)
	HIncrByFloat(key string, field string, increment float64) (val float64, err error)
	HKeys(key string) (fields []string, err error)
	HVals(key string) (values []string, err error)
	HLen(key string) (length int, err error)

	//-----------------List--------------------------
	LLen(key string) (listLength int, err error)
	LPush(key string, values ...interface{}) (listLength int, err error)
	LPushX(key string, value interface{}) (listLength int, err error)
	LPop(key string) (value string, err error)
	LIndex(key string, index int) (value string, err error)
	LRange(key string, start, stop int) (values []string, err error)
	LSet(key string, index int, value interface{}) (ok bool, err error)
	LTrim(key string, start, stop int) (ok bool, err error)
	RPush(key string, values ...interface{}) (listLength int, err error)
	RPushX(key string, value interface{}) (listLength int, err error)
	RPop(key string) (value string, err error)

	//--------------------Set---------------------------
	SAdd(key string, members ...interface{}) (addNum int, err error)
	SMembers(key string) (members []string, err error)
	SIsMember(key string, member interface{}) (exists bool, err error)
	SCard(key string) (count int, err error)
	SPop(key string) (member string, err error)
	SRandMember(key string, count int) (members []string, err error)
	SRem(key string, members ...interface{}) (removeNum int, err error)
	SMove(sourceSetKey, destinationSetKey string, member interface{}) (success int, err error)
	SDiff(keys ...interface{}) (members []string, err error)
	SDiffStore(destinationSetKey string, keys ...string) (memberCount int, err error)
	SInter(keys ...interface{}) (members []string, err error)
	SInterStore(destinationSetKey string, keys ...string) (memberCount int, err error)
	SUnion(keys ...interface{}) (members []string, err error)
	SUnionStore(destinationSetKey string, keys ...string) (memberCount int, err error)
	SScan(key string, cursor int, match string, count int) (newCursor int, keys []string, err error)

	//--------------------ZSet---------------------------
	ZAdd(key string, score, value interface{}, scoreAndValues ...interface{}) (createNum int, err error)
	ZAddMap(key string, membersMap map[string]interface{}) (createNum int, err error)
	ZCard(key string) (count int, err error)
	ZCount(key string, minScore, maxScore interface{}) (count int, err error)
	ZIncrBy(key string, increment interface{}, member string) (newScore string, err error)
	ZRange(key string, startIndex, stopIndex int) (members []string, err error)
	ZRevRange(key string, startIndex, stopIndex int) (members []string, err error)
	ZRangeWithScore(key string, startIndex, stopIndex int) (members map[string]string, err error)
	ZRevRangeWithScore(key string, startIndex, stopIndex int) (members map[string]string, err error)
	ZRangeByScore(key string, minScore, maxScore interface{}, offset, limit int) (members []string, err error)
	ZRevRangeByScore(key string, maxScore, minScore interface{}, offset, limit int) (members []string, err error)
	ZRangeByScoreWithScore(key string, minScore, maxScore interface{}, offset, limit int) (members map[string]string, err error)
	ZRevRangeByScoreWithScore(key string, maxScore, minScore interface{}, offset, limit int) (members map[string]string, err error)
	ZRank(key, member string) (rankIndex int, err error)
	ZRevRank(key, member string) (rankIndex int, err error)
	ZScore(key, member string) (score string, err error)
	ZRem(key string, members ...interface{}) (removeNum int, err error)
	ZRemRangeByRank(key string, startIndex, stopIndex int) (removeNum int, err error)
	ZScan(key string, cursor int, match string, count int) (newCursor int, keys []string, err error)

	//----------------------Geo-----------------------------
	GeoAdd(key string, longitude, latitude float64, member interface{}, args ...interface{}) (createNum int, err error)
	GeoHash(key string, members ...interface{}) (hashList []string, err error)
	GeoDel(key string, members ...interface{}) (removeNum int, err error)
	GeoDist(key string, member1, member2 interface{}, unit string) (distance string, err error)
	GeoPos(key string, members ...interface{}) (positionList []Position, err error)
	GeoRadius(key string, longitude, latitude float64, radius interface{}, unit string, count int, sort string) (locationList []Location, err error)
	GeoRadiusByMember(key string, member interface{}, radius interface{}, unit string, count int, sort string) (locationList []Location, err error)

	//--------------------Pub/Sub---------------------------
	Publish(channel string, msg string) (receiveNum int, err error)
	PubSubChannels(pattern string) (channels []string, err error)

	//--------------------Script---------------------------
	EvalOrSha(script *redigo.Script, keysAndArgs ...interface{}) (reply interface{}, err error)
	EvalOrSha4Int64(script *redigo.Script, keysAndArgs ...interface{}) (res int64, err error)
	EvalOrSha4String(script *redigo.Script, keysAndArgs ...interface{}) (res string, err error)

	//--------------------Transaction---------------------------
	Exec(multi Multi) (values []interface{}, err error)

	//--------------------Lock/Limit/Cache---------------------------
	Acquire(key string, timeoutSecond int) (token int64, err error)
	Release(key string, token int64) (ok bool, err error)
	LevelCache(localCache *sync.Map, key string, current, timeoutSecond int64, handler Handler) (value []byte, err error)
	CacheGet(key string, current, timeoutSecond int64, handler Handler) (value []byte, err error)
	CacheGetItem(key string, current, timeoutSecond int64, handler Handler) (item Item, err error)
	CacheRemove(key string) (ok bool, err error)
	GetToken(key string, current int64, capacity, rate, reqNum, keyTimeoutSecond int) (ok bool, err error)
	SecondLimitByToken(key string, limit int, reqNum int) (ok bool, err error)
	SecondLimitByTime(key string, limit int, reqNum int) (ok bool, err error)
	MinuteLimitByTime(key string, limit int, reqNum int) (ok bool, err error)
	HourLimitByTime(key string, limit int, reqNum int) (ok bool, err error)
	DayLimitByTime(key string, limit int, reqNum int) (ok bool, err error)

	//-----------------Server--------------------------
	ClientList() (clients []string, err error)
	ConfigGet(pattern string) (conf map[string]string, err error)
	ConfigSet(param string, value interface{}) (ok bool, err error)
}

func GetPool added in v1.0.3

func GetPool(key string) Pool

func NewPool

func NewPool(option Option) (p Pool)

NewPool 实例化Pool

func NewPoolWithJson added in v1.0.3

func NewPoolWithJson(jsonStr string) (p Pool, err error)

NewPoolWithJson 实例化Pool

type Position

type Position struct {
	Lng float64
	Lat float64
}

Position 经纬度位置

func Positions

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

Positions 转换为Position信息

type SubConn

type SubConn interface {
	Close() error
	Subscribe(channels ...interface{}) error
	SubscribeChannel(ctx context.Context, size int, channels ...interface{}) (ch <-chan interface{}, err error)
	PSubscribe(channels ...interface{}) error
	PSubscribeChannel(ctx context.Context, size int, channels ...interface{}) (ch <-chan interface{}, err error)
	Unsubscribe(channels ...interface{}) error
	PUnsubscribe(channels ...interface{}) error
	Ping(data string) error
	Receive() interface{}
	ReceiveWithTimeout(timeout time.Duration) interface{}
}

func NewSubConn

func NewSubConn(option Option) (SubConn, error)

type Subscription

type Subscription struct {
	Kind    string
	Channel string
	Count   int
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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