redis

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: GPL-3.0 Imports: 14 Imported by: 2

README

gone-redis

This lib integrated the basic operation of redis with redigo.

How to Use

0. Redis Server Config

The Lib use the gone-config, so we can config in config files(config/default.properties, config/${env}.properties).

  • redis.server: Redis server address, example: localhost:6379.
  • redis.password: Redis server password.
  • redis.db: Redis db index, which you want to use.
  • redis.max-idle: Idle connection count in the redis connection pool.
  • redis.max-active: Max active connection count in the redis connection pool.
  • redis.cache.prefix: A prefix string use to isolate different applications. It's recommended, if Your redis is used by multiple applications. if redis.cache.prefix=app-x, Cache.Set("the-module-cache-key", value) will set value on redis key: app-x#the-module-cache-key .
1. Distributed Cache with Redis
package demo

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
)

func NewService() gone.Goner {
	return &service{}
}

type service struct {
	gone.Flag
	cache redis.Cache `gone:"gone-redis-cache"` //Tag label
}

func (s *service) Use() {

	type ValueStruct struct {
		X int
		Y int
		//...
	}

	var v ValueStruct

	// set cache to redis
	err := s.cache.Set("cache-key", v)
	if err != nil {
		//deal err
	}

	//get value from cache
	err = s.cache.Get("cache-key", &v)
	if err != nil {
		//deal err
	}

	//...
}
2. Distributed Locks with Redis
package demo

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
	"time"
)

func NewService() gone.Goner {
	return &service{}
}

type service struct {
	gone.Flag
	locker redis.Locker `gone:"gone-redis-locker"`
}

//UseTryLock use Locker.TryLock
func (s *service) UseTryLock() {
	unlock, err := s.locker.TryLock("a-lock-key-in-redis", 10*time.Second)
	if err != nil {
		// deal err
	}
	defer unlock()
	// ... other operations
}

//UseLockAndDo use Locker.LockAndDo
func (s *service) UseLockAndDo() {
	err := s.locker.LockAndDo("a-lock-key-in-redis", func() {
		//do your business
		//...
		//It's automatically unlocked at the end of the function.
		//Otherwise, the lock will be automatically renewed until the function is finished.

	}, 10*time.Second, 2*time.Second)

	if err != nil {
		//deal err
	}
}
3. Operations on Key
package demo

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
	"time"
)

func NewService() gone.Goner {
	return &service{}
}

type service struct {
	gone.Flag
	key redis.Key `gone:"gone-redis-locker"`
}

func (s *service) UseTryLock() {

	// set the expiry time 
	s.key.Expire("the-key-in-redis", 2*time.Second)
	s.key.ExpireAt("the-key-in-redis", time.Now().Add(10*time.Minute))

	// get key ttl
	s.key.Ttl("the-key-in-redis")

	// and so on
}
4. Redis hashes
package demo

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
)

func NewService() gone.Goner {
	return &service{}
}

type service struct {
	gone.Flag
	h redis.Hash `gone:"gone-redis-provider,key-in-redis"` //use gone-redis-provider tag provide a redis.Hash to operate Hashes on `key-in-redis`
}

func (s *service) Use() {
	s.h.Set("a-field", "some thing")
	var str string
	s.h.Get("a-field", &str)

	//...
}
5. Provider

Provider can isolate key namespace in app again. For Example, you want use app-x#module-a as redis prefix for module A, and use app-x#module-b as redis prefix for module B. You can use it like below.

package A

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
)

//in module A
//...
type service struct {
	gone.Flag
	cache  redis.Cache  `gone:"gone-redis-provider,module-a"` //use cache 
	key    redis.Key    `gone:"gone-redis-provider,module-a"` //use key
	locker redis.Locker `gone:"gone-redis-provider,module-a"` //use locker
}
package B

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
)

//in module B
//...
type service struct {
	gone.Flag
	cache  redis.Cache  `gone:"gone-redis-provider,module-b"` //use cache 
	key    redis.Key    `gone:"gone-redis-provider,module-b"` //use key
	locker redis.Locker `gone:"gone-redis-provider,module-b"` //use locker
}

If the key value is in config files, you can use gone:"gone-redis-provider,config=config-file-key,default=default-val" .

package A

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner/redis"
)

//in module B
//...
type service struct {
	gone.Flag
	cache redis.Cache `gone:"gone-redis-provider,config=app.module-a.redis.prefix"` //use cache
}
5. Redis Pool

You can use redis.Pool directly to read/write redis, which provided by redigo.

package demo

import (
	"github.com/gone-io/gone/goner/redis"
	"github.com/gone-io/gone"
)

type service struct {
	gone.Flag
	pool redis.Pool `gone:"gone-redis-pool"`
}

func (s *service) Use() {
	conn := s.pool.Get()
	defer s.pool.Close(conn)

	//do some operation
	//conn.Do(/*...*/)

	//send a command
	//conn.Send(/*...*/)
}

Test

The test script below depend on Make and Docker which is used to run redis.

make test

Documentation

Index

Constants

View Source
const (
	//CacheProviderNeedKey cache provider need a key
	CacheProviderNeedKey = 1501 + iota
	KeyNoExpiration
)
View Source
const IdGoneRedisInner = "gone-redis-inner"

Variables

View Source
var (
	ErrNil           = redis.ErrNil
	ErrNotExpire     = KeyNoExpirationError()
	Int              = redis.Int
	Int64            = redis.Int64
	Uint64           = redis.Uint64
	Float64          = redis.Float64
	String           = redis.String
	Bytes            = redis.Bytes
	Bool             = redis.Bool
	Values           = redis.Values
	Float64s         = redis.Float64s
	Strings          = redis.Strings
	ByteSlices       = redis.ByteSlices
	Int64s           = redis.Int64s
	Ints             = redis.Ints
	StringMap        = redis.StringMap
	IntMap           = redis.IntMap
	Int64Map         = redis.Int64Map
	Float64Map       = redis.Float64Map
	Positions        = redis.Positions
	Uint64s          = redis.Uint64s
	Uint64Map        = redis.Uint64Map
	SlowLogs         = redis.SlowLogs
	Latencies        = redis.Latencies
	LatencyHistories = redis.LatencyHistories
)
View Source
var ErrorLockFailed = errors.New("not lock success")

Functions

func CacheProviderNeedKeyError added in v0.0.21

func CacheProviderNeedKeyError() gone.Error

func KeyNoExpirationError added in v0.0.21

func KeyNoExpirationError() gone.Error

func NewCacheProvider added in v0.0.21

func NewCacheProvider() (gone.Vampire, gone.GonerId)

func NewInner

func NewInner() (gone.Goner, gone.GonerId)

func NewRedisCache

func NewRedisCache() (gone.Goner, gone.GonerId)

func NewRedisLocker

func NewRedisLocker() (gone.Goner, gone.GonerId)

func NewRedisPool

func NewRedisPool() (gone.Angel, gone.GonerId)

func Priest

func Priest(cemetery gone.Cemetery) error

Types

type Cache

type Cache interface {
	Put(key string, value any, ttl ...time.Duration) error
	Set(key string, value any, ttl ...time.Duration) error
	Get(key string, value any) error
	Remove(key string) (err error)

	Keys(key string) ([]string, error)

	//Prefix get key prefix in redis
	Prefix() string
}

Cache redis cache, which use redis string to store value(encoded to json) HOW TO USE

type GoneComponent struct {
	redis.Cache `gone:"gone-redis-cache"`
}

func (c *GoneComponent) useRedisCache(){
	key := "test"
	value := map[string]interface{}{
		"some": "string"
	}

	c.Put(key, value) //store value to redis key
	c.Get(key, &value)//fetch value from redis
}

type Conn added in v0.0.13

type Conn = redis.Conn

type Hash added in v0.0.21

type Hash interface {
	Set(field string, v interface{}) (err error)
	Get(field string, v interface{}) error

	Del(field string) error
	Scan(func(field string, v []byte)) error

	Incr(field string, increment int64) (int64, error)
}

type Key added in v0.0.21

type Key interface {
	Expire(key string, ttl time.Duration) error
	ExpireAt(key string, time time.Time) error
	Ttl(key string) (time.Duration, error)
	Del(key string) (err error)
	Incr(field string, increment int64) (int64, error)
	Keys(key string) ([]string, error)
	Prefix() string
}

type Locker

type Locker interface {
	TryLock(key string, ttl time.Duration) (unlock Unlock, err error)
	LockAndDo(key string, fn func(), lockTime, checkPeriod time.Duration) (err error)
}

Locker redis Distributed lock

type Pool added in v0.0.10

type Pool interface {
	Get() Conn
	Close(conn redis.Conn)
}

type Unlock

type Unlock func()

Jump to

Keyboard shortcuts

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