jcache

package module
v2.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2023 License: MIT Imports: 7 Imported by: 2

README

JCache - High-Availability Multi-Level Cache Integration Library in Golang [中文版]

Introduction

  • This project is a Golang library that can be used by Golang projects. You can use it by running go get github.com/jerbe/jcache/v2.
  • This project is a lightweight multi-level cache integration solution inspired by Redis.
  • It can run multiple drivers simultaneously without interference.
  • Supports the Redis driver or custom drivers, as long as they implement the driver.Cache interface.
  • Built-in memory cache driver.
  • The memory driver supports distribution, based on ETCD service discovery and election strategy. It selects one instance as the master node, and the rest as slave nodes. Every operation on the master node is synchronized to the other slave nodes via a gRPC interface, and write operations on slave nodes are first sent to the master node via gRPC and then synchronized to the other slave nodes to achieve high availability and data consistency.

Basic Architecture

At the current stage, functionality is prioritized, and in the future, the priority retrieval order may be specified based on the driver's weight. The current version's priority order is determined by the driver order specified when instantiating the client.

// Instantiate a client with Redis as the preferred driver and memory driver as the fallback.
client := jcache.NewClient(driver.NewRedis(), driver.NewMemory())


// Instantiate a client with memory driver as the preferred driver and Redis as the fallback.
client := jcache.NewClient(driver.NewMemory(), driver.NewRedis())
Basic Architecture Diagram

Progress

  • Redis driver support
  • Native memory driver support
  • Standalone mode support
    • Distributed mode support
      • Incremental synchronization of slave nodes
      • Full synchronization of nodes

Examples

  go get github.com/jerbe/jcache/v2
import (
    "time"
	
    "github.com/jerbe/jcache/v2"
    "github.com/jerbe/jcache/v2/driver"
)

func main(){
// Instantiate a cache client with memory as the driver
    client := jcache.NewClient()

// Instantiate a distributed memory cache client
    cfg := driver.DistributeMemoryConfig{
		Port: 10080,         // Port for starting the gRPC server, please set different ports for the same machine
        Prefix: "/prefix",   // Set the corresponding prefix according to your business needs
		// EtcdCfg is set according to the configuration of your deployed ETCD service
        EtcdCfg: clientv3.Config{
			Endpoints: []string{"127.0.0.1:2379"}
		}
    }
	client := driver.NewDistributeMemory(cfg)



// Client that supports all operations, including String, Hash, List, etc.
	client := jcache.NewClient(driver.NewMemory())
	client.Set(context.Background(),"hello","world", time.Hour)
	client.Get(context.Background(),"hello")
	client.MGet(context.Background(),"hello","hi")
	...

    // Client that supports only String operations
	stringClient := jcache.NewStringClien(driver.NewMemory()); 
	stringClient.Set(context.Background(),"hello","world", time.Hour)
	stringClient.Get(context.Background(),"hello")
	stringClient.MGet(context.Background(),"hello","hi")
	...

    // Client that supports only Hash operations
	hashClient := jcache.NewHashClient(driver.NewMemory()); 
	hashClient.HSet(context.Background(),"hello","world","boom")
	hashClient.HGet(context.Background(),"hello","world")
	...

// Client that supports only List operations
	listClient := jcache.NewListClient(driver.NewMemory());
	listClient.Push(context.Background(),"hello","world")
	listClient.Pop(context.Background(),"hello")
	listClient.Shift(context.Background(),"hello")
}

Documentation

Index

Constants

View Source
const (
	// KeepTTL 保持原先的过期时间(TTL)
	KeepTTL = -1

	// DefaultEmptySetNXDuration 默认空对象设置过期时效
	DefaultEmptySetNXDuration = time.Second * 10

	// DefaultExpirationDuration 默认缓存过期时效
	DefaultExpirationDuration = time.Hour
)

Variables

View Source
var (
	Nil              = errors.Nil
	ErrNoCacheClient = errors.ErrNoCacheClient
)

Functions

func RandomExpirationDuration

func RandomExpirationDuration() time.Duration

RandomExpirationDuration 以 DefaultExpirationDuration 为基础,返回一个 DefaultExpirationDuration ± 30m 内的时间长度

Types

type BaseClient added in v2.1.0

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

func (*BaseClient) Del added in v2.1.0

func (cli *BaseClient) Del(ctx context.Context, keys ...string) driver.IntValuer

Del 删除键

func (*BaseClient) Exists added in v2.1.0

func (cli *BaseClient) Exists(ctx context.Context, keys ...string) driver.IntValuer

Exists 判断某个Key是否存在

func (*BaseClient) Expire added in v2.1.0

func (cli *BaseClient) Expire(ctx context.Context, key string, expiration time.Duration) driver.BoolValuer

Expire 设置某个Key的TTL时长

func (*BaseClient) ExpireAt added in v2.1.0

func (cli *BaseClient) ExpireAt(ctx context.Context, key string, at time.Time) driver.BoolValuer

ExpireAt 设置某个key在指定时间内到期

func (*BaseClient) Persist added in v2.1.2

func (cli *BaseClient) Persist(ctx context.Context, key string) driver.BoolValuer

Persist 设置某个key成为持久性的

type Client

func NewClient

func NewClient(drivers ...driver.Cache) *Client

NewClient 实例化出一个客户端

type HashClient

type HashClient struct {
	BaseClient
}

func NewHashClient

func NewHashClient(drivers ...driver.Hash) *HashClient

func (*HashClient) HDel

func (cli *HashClient) HDel(ctx context.Context, key string, fields ...string) driver.IntValuer

HDel 删除hash数据

func (*HashClient) HExists

func (cli *HashClient) HExists(ctx context.Context, key, field string) driver.BoolValuer

HExists 判断哈希表周公某个字段是否存在

func (*HashClient) HGet

func (cli *HashClient) HGet(ctx context.Context, key, field string) driver.StringValuer

HGet 获取Hash表指定字段的值

func (*HashClient) HGetAll

HGetAll 获取哈希表中所有的值,包括键/值

func (*HashClient) HGetAndScan

func (cli *HashClient) HGetAndScan(ctx context.Context, dst interface{}, key, field string) error

HGetAndScan 获取Hash表指定字段的值

func (*HashClient) HKeys

HKeys 获取Hash表的所有键

func (*HashClient) HKeysAndScan

func (cli *HashClient) HKeysAndScan(ctx context.Context, dst interface{}, key string) error

HKeysAndScan 获取Hash表的所有键并扫描到dst中

func (*HashClient) HLen

func (cli *HashClient) HLen(ctx context.Context, key string) driver.IntValuer

HLen 获取Hash表的所有键个数

func (*HashClient) HMGet

func (cli *HashClient) HMGet(ctx context.Context, key string, fields ...string) driver.SliceValuer

HMGet 获取Hash表指定字段的值

func (*HashClient) HMGetAndScan

func (cli *HashClient) HMGetAndScan(ctx context.Context, dst interface{}, key string, fields ...string) error

HMGetAndScan 获取Hash表指定字段的值并扫描进入到dst中

func (*HashClient) HSet

func (cli *HashClient) HSet(ctx context.Context, key string, values ...interface{}) driver.IntValuer

HSet 写入hash数据 接受以下格式的值: HSet("myhash", "key1", "value1", "key2", "value2")

HSet("myhash", []string{"key1", "value1", "key2", "value2"})

HSet("myhash", map[string]interface{}{"key1": "value1", "key2": "value2"}) 使用“redis”标签播放结构。 type MyHash struct { Key1 string `redis:"key1"`; Key2 int `redis:"key2"` }

HSet("myhash", MyHash{"value1", "value2"}) 警告:redis-server >= 4.0 对于struct,可以是结构体指针类型,我们只解析标签为redis的字段。如果你不想读取该字段,可以使用 `redis:"-"` 标志来忽略它,或者不需要设置 redis 标签。对于结构体字段的类型,我们只支持简单的数据类型:string、int/uint(8,16,32,64)、float(32,64)、time.Time(to RFC3339Nano)、time.Duration(to Nanoseconds) ),如果是其他更复杂或者自定义的数据类型,请实现encoding.BinaryMarshaler接口。

func (*HashClient) HSetNX

func (cli *HashClient) HSetNX(ctx context.Context, key, field string, data interface{}) driver.BoolValuer

HSetNX 哈希表设置某个字段的值,如果存在的话返回true

func (*HashClient) HVals

HVals 获取Hash表的所有值

func (*HashClient) HValsAndScan

func (cli *HashClient) HValsAndScan(ctx context.Context, dst interface{}, key string) error

HValsAndScan 获取Hash表的所有值并扫如dst中

type ListClient

type ListClient struct {
	BaseClient
}

func NewListClient

func NewListClient(drivers ...driver.List) *ListClient

func (*ListClient) LLen

func (cli *ListClient) LLen(ctx context.Context, key string) driver.IntValuer

LLen 返回列表长度

func (*ListClient) LPop

func (cli *ListClient) LPop(ctx context.Context, key string) driver.StringValuer

LPop 移除并取出列表内的最后一个元素

func (*ListClient) LPopAndScan

func (cli *ListClient) LPopAndScan(ctx context.Context, dst interface{}, key string) error

LPopAndScan 通过扫描方式移除并取出列表内的最后一个元素

func (*ListClient) LPush

func (cli *ListClient) LPush(ctx context.Context, key string, data ...interface{}) driver.IntValuer

LPush 推送数据

func (*ListClient) LRang

func (cli *ListClient) LRang(ctx context.Context, key string, start, stop int64) driver.StringSliceValuer

LRang 获取列表内的范围数据

func (*ListClient) LRangAndScan

func (cli *ListClient) LRangAndScan(ctx context.Context, dst interface{}, key string, start, stop int64) error

LRangAndScan 通过扫描方式获取列表内的范围内数据

func (*ListClient) LShift

func (cli *ListClient) LShift(ctx context.Context, key string) driver.StringValuer

LShift 移除并取出列表内的第一个元素

func (*ListClient) LShiftAndScan

func (cli *ListClient) LShiftAndScan(ctx context.Context, dst interface{}, key string) error

LShiftAndScan 通过扫描方式移除并取出列表内的第一个元素

func (*ListClient) LTrim

func (cli *ListClient) LTrim(ctx context.Context, key string, start, stop int64) driver.StatusValuer

LTrim 获取列表内的范围数据

type SortedSetClient added in v2.1.2

type SortedSetClient struct {
	BaseClient
}

SortedSetClient 已排序的集合客户端

func NewSortedSetClient added in v2.1.2

func NewSortedSetClient(drivers ...driver.SortedSet) *SortedSetClient

NewSortedSetClient 返回一个已排序的集合客户端

func (*SortedSetClient) ZAdd added in v2.1.2

func (cli *SortedSetClient) ZAdd(ctx context.Context, key string, members ...driver.Z) driver.IntValuer

ZAdd 添加有序集合的元素

func (*SortedSetClient) ZCard added in v2.1.2

func (cli *SortedSetClient) ZCard(ctx context.Context, key string) driver.IntValuer

ZCard 获取有序集合的元素数量

func (*SortedSetClient) ZCount added in v2.1.2

func (cli *SortedSetClient) ZCount(ctx context.Context, key, min, max string) driver.IntValuer

ZCount 返回有序集 key 中, score 值在 min 和 max 之间(默认包括 score 值等于 min 或 max )的成员的数量。

func (*SortedSetClient) ZIncrBy added in v2.1.2

func (cli *SortedSetClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) driver.FloatValuer

ZIncrBy 为有序集 key 的成员 member 的 score 值加上增量 increment 。 可以通过传递一个负数值 increment ,让 score 减去相应的值,比如 ZINCRBY key -5 member ,就是让 member 的 score 值减去 5 @return member 成员的新 score 值

func (*SortedSetClient) ZRange added in v2.1.2

func (cli *SortedSetClient) ZRange(ctx context.Context, key string, start, stop int64) driver.StringSliceValuer

ZRange 返回有序集 key 中,指定区间内的成员。 其中成员的位置按 score 值递增(从小到大)来排序。 具有相同 score 值的成员按字典序(lexicographical order )来排列。 如果你需要成员按 score 值递减(从大到小)来排列,请使用 ZREVRANGE 命令。 下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。 你也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推。

func (*SortedSetClient) ZRangeByScore added in v2.1.2

func (cli *SortedSetClient) ZRangeByScore(ctx context.Context, key string, opt *driver.ZRangeBy) driver.StringSliceValuer

ZRangeByScore 返回有序集 key 中,所有 score 值介于 min 和 max 之间(包括等于 min 或 max )的成员。有序集成员按 score 值递增(从小到大)次序排列。 具有相同 score 值的成员按字典序(lexicographical order)来排列(该属性是有序集提供的,不需要额外的计算)。 可选的 LIMIT 参数指定返回结果的数量及区间(就像SQL中的 SELECT LIMIT offset, count ),注意当 offset 很大时,定位 offset 的操作可能需要遍历整个有序集,此过程最坏复杂度为 O(N) 时间。

func (*SortedSetClient) ZRank added in v2.1.2

func (cli *SortedSetClient) ZRank(ctx context.Context, key, member string) driver.IntValuer

ZRank 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列。 排名以 0 为底,也就是说, score 值最小的成员排名为 0 。

func (*SortedSetClient) ZRem added in v2.1.2

func (cli *SortedSetClient) ZRem(ctx context.Context, key string, members ...interface{}) driver.IntValuer

ZRem 移除有序集 key 中的一个或多个成员,不存在的成员将被忽略。 @return 被成功移除的成员的数量,不包括被忽略的成员

func (*SortedSetClient) ZRemRangeByRank added in v2.1.2

func (cli *SortedSetClient) ZRemRangeByRank(ctx context.Context, key string, start, stop int64) driver.IntValuer

ZRemRangeByRank 移除有序集 key 中,指定排名(rank)区间内的所有成员。 区间分别以下标参数 start 和 stop 指出,包含 start 和 stop 在内。 下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。 你也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推。

func (*SortedSetClient) ZRemRangeByScore added in v2.1.2

func (cli *SortedSetClient) ZRemRangeByScore(ctx context.Context, key, min, max string) driver.IntValuer

ZRemRangeByScore 返回有序集 key 中,所有 score 值介于 min 和 max 之间(包括等于 min 或 max )的成员。 有序集成员按 score 值递增(从小到大)次序排列。

func (*SortedSetClient) ZRevRange added in v2.1.2

func (cli *SortedSetClient) ZRevRange(ctx context.Context, key string, start, stop int64) driver.StringSliceValuer

ZRevRange 返回有序集 key 中,指定区间内的成员。 其中成员的位置按 score 值递减(从大到小)来排列。 具有相同 score 值的成员按字典序的逆序(reverse lexicographical order)排列。

func (*SortedSetClient) ZRevRank added in v2.1.2

func (cli *SortedSetClient) ZRevRank(ctx context.Context, key, member string) driver.IntValuer

ZRevRank 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递减(从大到小)排序。 排名以 0 为底,也就是说, score 值最大的成员排名为 0 。

func (*SortedSetClient) ZScore added in v2.1.2

func (cli *SortedSetClient) ZScore(ctx context.Context, key, member string) driver.FloatValuer

ZScore 返回有序集 key 中,成员 member 的 score 值。 如果 member 元素不是有序集 key 的成员,或 key 不存在,返回 nil 。

type StringClient

type StringClient struct {
	BaseClient
}

func NewStringClient

func NewStringClient(drivers ...driver.String) *StringClient

func (*StringClient) Get

Get 获取数据

func (*StringClient) GetAndScan

func (cli *StringClient) GetAndScan(ctx context.Context, dst interface{}, key string) error

GetAndScan 获取并扫描

func (*StringClient) MGet

func (cli *StringClient) MGet(ctx context.Context, keys ...string) driver.SliceValuer

MGet 获取多个Keys的值

func (*StringClient) MGetAndScan

func (cli *StringClient) MGetAndScan(ctx context.Context, dst interface{}, keys ...string) error

MGetAndScan 获取多个Keys的值并扫描进dst中

func (*StringClient) Set

func (cli *StringClient) Set(ctx context.Context, key string, data interface{}, expiration time.Duration) driver.StatusValuer

Set 设置数据

func (*StringClient) SetNX

func (cli *StringClient) SetNX(ctx context.Context, key string, data interface{}, expiration time.Duration) driver.BoolValuer

SetNX 设置数据,如果key不存在的话

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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