Import path:
gitlab.soludian.com/soludian/fountain/libs/stored/fedis
fedis
import "gitlab.soludian.com/soludian/fountain/libs/stored/fedis"Index
- Constants
- Variables
- func AddAddrs(addrs ...string) lib_3rd.Option[config]
- func CreateCtx(ctx context.Context) (context.Context, context.CancelFunc)
- func CreateDefaultCtx() (context.Context, context.CancelFunc)
- func CreateDeletePattern(client *Client, ctx context.Context, pattern string, batchSize ...int64) []rueidis.Completed
- func CreatePageListDataKey(args any) (string, string)
- func CreateStatWindowKey(windowStartTime int32, args any) string
- func Delete(client *Client, keyFn func(string) string, ids ...string) error
- func DeleteCtx(client *Client, ctx context.Context, keyFn func(string) string, ids ...string) error
- func Deletes(client *Client, keys ...string) error
- func DeletesCtx(client *Client, ctx context.Context, keys ...string) error
- func Get[T any](client *Client, key string) T
- func GetCtx[T any](client *Client, ctx context.Context, key string) T
- func GetExist[T any](client *Client, key string) (T, bool)
- func GetExistCtx[T any](client *Client, ctx context.Context, key string) (T, bool)
- func GetHashFieldSet[T any](client *Client, key string, args any) T
- func GetHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, args any) T
- func GetRef[T any](client *Client, key string) T
- func GetRefCtx[T any](client *Client, ctx context.Context, key string) T
- func GetsByIDs[T any](client *Client, keyFn func(string) string, ids ...string) []T
- func GetsByIDsCtx[T any](client *Client, ctx context.Context, keyFn func(string) string, ids ...string) []T
- func GetsListPage[T any](client *Client, hashKey string, args ...any) ([]T, int)
- func GetsListPageCtx[T any](client *Client, ctx context.Context, hashKey string, args ...any) ([]T, int)
- func IncrementWindowCounterValid(client *Client, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64
- func IncrementWindowCounterValidCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64
- func IncrementWindowCounterValidWithCountCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter, count int32, args ...any) int64
- func ResetWindowCounter(client *Client, windowSlideInterval int32, args ...any) error
- func Save(client *Client, key string, expiration time.Duration, md any) error
- func SaveCtx(client *Client, ctx context.Context, key string, expiration time.Duration, md any) error
- func SaveHashFieldSet[T any](client *Client, key string, data T, args any) error
- func SaveHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, data T, args any) error
- func SaveHashFieldSetTTL[T any](client *Client, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) error
- func SaveHashFieldSetTTLCtx[T any](client *Client, ctx context.Context, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) error
- func SaveListPage[T any](client *Client, hashKey string, data []T, total int, args ...any) error
- func SaveListPageCtx[T any](client *Client, ctx context.Context, hashKey string, data []T, total int, args ...any) error
- func SaveSet[T IDer](client *Client, keyFn func(string) string, expiration time.Duration, mds ...*T) error
- func SaveSetCtx[T IDer](client *Client, ctx context.Context, keyFn func(string) string, expiration time.Duration, mds ...*T) error
- func SaveSetKeys(client *Client, md any, expiration time.Duration, keys ...string) error
- func SaveSetKeysCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) error
- func SaveSetKeysRef(client *Client, md any, expiration time.Duration, keys ...string) error
- func SaveSetKeysRefCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) error
- func SaveSets[T IDer](client *Client, keyFns []func(string) string, expiration time.Duration, mds ...*T) error
- func SaveSetsCtx[T IDer](client *Client, ctx context.Context, keyFns []func(string) string, expiration time.Duration, mds ...*T) error
- func WithAccessInterceptor(enable bool) lib_3rd.Option[config]
- func WithAccessInterceptorReq(enable bool) lib_3rd.Option[config]
- func WithAccessInterceptorRes(enable bool) lib_3rd.Option[config]
- func WithAddrs(addrs ...string) lib_3rd.Option[config]
- func WithConfig(conf *config) lib_3rd.Option[config]
- func WithDBNum(num int) lib_3rd.Option[config]
- func WithDebugMode(enable bool) lib_3rd.Option[config]
- func WithEnvironment(env string) lib_3rd.Option[config]
- func WithLogger(logger ...flog.FlogInf) lib_3rd.Option[config]
- func WithMasterName(name string) lib_3rd.Option[config]
- func WithMaxActiveConns(max int) lib_3rd.Option[config]
- func WithMaxIdleConns(max int) lib_3rd.Option[config]
- func WithMaxRetries(max int) lib_3rd.Option[config]
- func WithMetricInterceptor(enable bool) lib_3rd.Option[config]
- func WithMinIdleConns(min int) lib_3rd.Option[config]
- func WithName(name string) lib_3rd.Option[config]
- func WithOnFail(onFail string) lib_3rd.Option[config]
- func WithPassword(password string) lib_3rd.Option[config]
- func WithPoolSize(size int) lib_3rd.Option[config]
- func WithPoolTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithReadOnlyMode(enable bool) lib_3rd.Option[config]
- func WithReadTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithSlowLogThreshold(threshold time.Duration) lib_3rd.Option[config]
- func WithStatServerName(name string) lib_3rd.Option[config]
- func WithTraceInterceptor(enable bool) lib_3rd.Option[config]
- func WithWriteTimeout(timeout time.Duration) lib_3rd.Option[config]
- type Client
- func (c *Client) Client() rueidis.Client
- func (c *Client) ClientBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64, opts ...rueidisprob.BloomFilterOptionFunc) (rueidisprob.BloomFilter, error)
- func (c *Client) ClientCompact() rueidiscompat.Cmdable
- func (c *Client) ClientCountingBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64) (rueidisprob.CountingBloomFilter, error)
- func (c *Client) ClientNewSlidingBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64, windowSize time.Duration, opts ...rueidisprob.SlidingBloomFilterOptionFunc) (rueidisprob.BloomFilter, error)
- func (c *Client) Close() error
- func (c *Client) Connection() rueidis.Client
- func (c *Client) Liveness() bool
- func (c *Client) LockClient() *lockClient
- func (c *Client) Logger() flog.FlogInf
- func (c *Client) Readiness() bool
- type Err
- type IDer
- type Lock
- type LockOption
- type PoolStats
- type RetryStrategy
Constants
const (
KDefaultTimeout = 15 * time.Second
// KModeCluster using clusterClient
KModeCluster string = "cluster"
// KModeStub using stubClient
KModeStub string = "stub"
// KModeSentinel using Failover sentinel client
KModeSentinel string = "sentinel"
)const (
// ErrInvalidParams is returned when parameters is invalid.
ErrInvalidParams = Err("invalid params")
// ErrNotObtained is returned when a Lock cannot be obtained.
ErrNotObtained = Err("redis_lock: not obtained")
// ErrLockNotHeld is returned when trying to release an inactive Lock.
ErrLockNotHeld = Err("redis_lock: lock not held")
)const KPackageName = "fedis"Variables
var GetFountainInstance = Lib.GetFountainInstancevar GetFountainManager = Lib.GetFountainManagerSử dụng khi config instance ở dạng key:value; Nếu config instance ở dạng key:array thì sử dụng hàm InstallFountainInstances Nếu config ở dạng key:array thì sẽ chỉ install config phần tử đầu tiên mà thôi
Install with config format <key>:<value>; eg: fedis:<value>
Usage:
config.yaml:
fedis:
name: default_name
...
code.go
fedis.InstallFountainInstance()
fedis.WithConfigKey("fedis").InstallFountainInstance()var InstallFountainInstance = Lib.InstallFountainInstanceSử dụng khi config instance ở dạng key:value; Nếu config ở dạng key:array thì sẽ chỉ install config phần tử đầu tiên mà thôi
Install with config format <key>:<value>; eg: fedis:<value>
Usage:
config.yaml:
fedis:
name: default_name
...
code.go
fedis.WithConfigKey("fedis").InstallFountainInstanceOnce()var InstallFountainInstanceOnce = Lib.InstallFountainInstanceOnceSử dụng khi config instance ở dạng key:array<value>; Sẽ luôn cố gắng khởi tạo kể cả khi config ở dạng key:value
Install with config format <key>:array<value>; eg: fedis:array<value>
Usage:
config.yaml:
fedis:
- name: default_name
...
code.go
fedis.InstallFountainInstances()
fedis.WithConfigKey("fedis").InstallFountainInstances()var InstallFountainInstances = Lib.InstallFountainInstancesTruy cập thẳng tới bộ quản lý thư viện
var Lib = lib_3rd.NewLib(newClient, lib_3rd.WithDefaultConfigsFunc[config, Client](DefaultConfigs), lib_3rd.WithStatsCollectors[config, Client](statsCollector))var WithConfigKey = Lib.WithConfigKeyfunc AddAddrs
func AddAddrs(addrs ...string) lib_3rd.Option[config]WithAddrs set addresses with host:port format
func CreateCtx
func CreateCtx(ctx context.Context) (context.Context, context.CancelFunc)Check ctx, create new context timeout if parent context have deadline
func CreateDefaultCtx
func CreateDefaultCtx() (context.Context, context.CancelFunc)func CreateDeletePattern
func CreateDeletePattern(client *Client, ctx context.Context, pattern string, batchSize ...int64) []rueidis.CompletedCreateDeletePattern quét Redis theo pattern và xóa các keys khớp sử dụng UNLINK (non-blocking). Hàm này sử dụng lệnh SCAN để tìm tất cả keys khớp với pattern, sau đó tạo batch commands để xóa.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- pattern: Pattern để tìm kiếm keys (hỗ trợ wildcard: * và ?)
- batchSize: Số lượng keys scan mỗi iteration (mặc định: 100)
Return:
- []rueidis.Completed: Danh sách các UNLINK commands đã build sẵn
Flow:
- Sử dụng SCAN để iterate qua tất cả keys trong Redis
- Với mỗi iteration, lọc keys khớp với pattern
- Build UNLINK command cho từng key tìm thấy
- Trả về danh sách commands để caller thực thi
Advantage:
- Sử dụng SCAN thay vì KEYS -> không block Redis server
- Sử dụng UNLINK thay vì DEL -> xóa async, không block
- Có thể control batch size để tối ưu performance
Note:
- Hàm CHỈ BUILD commands, KHÔNG thực thi xóa
- Caller phải tự thực thi commands trả về
- Context có thể bị cancel trong quá trình scan
- Nếu có lỗi, trả về nil và log error
Usage:
ctx := context.Background()
// Tìm và xóa tất cả user cache
commands := CreateDeletePattern(client, ctx, "user:*:cache")
if commands != nil {
results := client.Connection().DoMulti(ctx, commands...)
// Xử lý results...
}
// Tùy chỉnh batch size
commands = CreateDeletePattern(client, ctx, "session:*", 500)
// Xóa keys theo prefix cụ thể
commands = CreateDeletePattern(client, ctx, "temp:2024:*")func CreatePageListDataKey
func CreatePageListDataKey(args any) (string, string)Return field hash key and field total key
func CreateStatWindowKey
func CreateStatWindowKey(windowStartTime int32, args any) stringfunc Delete
func Delete(client *Client, keyFn func(string) string, ids ...string) errorDelete xóa nhiều objects theo IDs sử dụng context mặc định. Hàm này là wrapper cho DeleteCtx với context mặc định.
Parameters:
- client: Redis client instance
- keyFn: Hàm chuyển đổi ID thành Redis key
- ids: Danh sách các IDs cần xóa
Return:
- error: Trả về lỗi đầu tiên gặp phải (nếu có)
Features:
- Hỗ trợ wildcard pattern trong key từ keyFn
- Tự động xóa theo pattern nếu key chứa *
Usage:
// Xóa users theo IDs
keyFn := func(id string) string { return fmt.Sprintf("user:%s", id) }
err := Delete(client, keyFn, "1", "2", "3")
// Xóa tất cả cache của user
keyFn = func(id string) string { return fmt.Sprintf("user:%s:*", id) }
err = Delete(client, keyFn, "1")func DeleteCtx
func DeleteCtx(client *Client, ctx context.Context, keyFn func(string) string, ids ...string) errorDeleteCtx xóa nhiều objects theo IDs sử dụng custom context. Hàm này sử dụng keyFn để chuyển đổi IDs thành Redis keys.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- keyFn: Hàm chuyển đổi ID thành Redis key
- ids: Danh sách các IDs cần xóa
Return:
- error: Trả về lỗi đầu tiên gặp phải (nếu có)
Features:
- Hỗ trợ wildcard pattern (*) trong key từ keyFn
- Nếu key chứa *, sử dụng CreateDeletePattern để xóa theo pattern
- Xóa tất cả keys khớp với pattern bằng lệnh UNLINK (non-blocking)
Usage:
ctx := context.Background()
// Xóa theo IDs cụ thể
keyFn := func(id string) string { return fmt.Sprintf("user:%s", id) }
err := DeleteCtx(client, ctx, keyFn, "1", "2", "3")
// Xóa theo pattern wildcard
keyFn = func(id string) string { return fmt.Sprintf("user:%s:*", id) }
err = DeleteCtx(client, ctx, keyFn, "1") // Xóa tất cả keys user:1:*func Deletes
func Deletes(client *Client, keys ...string) errorDeletes xóa nhiều keys từ Redis sử dụng context mặc định. Hàm này là wrapper cho DeletesCtx với context mặc định.
Parameters:
- client: Redis client instance
- keys: Danh sách các keys cần xóa
Return:
- error: Trả về nil vì hàm không trả về lỗi (chỉ log lỗi)
Note:
- Hàm không hỗ trợ wildcard pattern (*)
- Đây là hàm thay thế cho DeleteListPage cũ
Usage:
// Xóa nhiều user keys
err := Deletes(client, "user:1", "user:2", "user:3")
// Xóa cache keys
err = Deletes(client, "cache:products", "cache:categories")func DeletesCtx
func DeletesCtx(client *Client, ctx context.Context, keys ...string) errorDeletesCtx xóa nhiều keys từ Redis sử dụng custom context. Hàm này sử dụng lệnh DEL để xóa các keys được chỉ định.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- keys: Danh sách các keys cần xóa
Return:
- error: Trả về nil vì hàm không trả về lỗi (chỉ log lỗi)
Note:
- Hàm không hỗ trợ wildcard pattern (*). Nếu key chứa *, sẽ hiển thị warning.
- Để xóa keys theo pattern, sử dụng DeletePattern hoặc DeleteCtx.
- Hàm luôn trả về nil mặc dù có lỗi xảy ra (chỉ log lỗi).
Usage:
ctx := context.Background()
err := DeletesCtx(client, ctx, "user:1", "user:2", "user:3")
// Xóa các cache keys
err = DeletesCtx(client, ctx, "cache:user:1", "cache:user:2")func Get
func Get[T any](client *Client, key string) TGet lấy dữ liệu từ Redis theo key và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T), với khả năng chuyển đổi kiểu (type conversion) thông minh.
Hàm này hỗ trợ các trường hợp chuyển đổi giữa dữ liệu JSON lưu trong Redis và các kiểu dữ liệu Go thông dụng.
Các kiểu dữ liệu được hỗ trợ:
- KIỂU CHUỖI (string):
- Lưu trong Redis: Bất kỳ giá trị JSON nào
- Lấy ra: giá trị gốc nếu lưu dạng string, dạng raw nếu lưu kiểu khác
- Ví dụ: "hello" → "hello", 123 → "123", true → "true", {"name":"John"} → `{"name":"John"}`
- KIỂU SỐ NGUYÊN (int, int8, int16, int32, int64):
- Lưu trong Redis: JSON number (int/float)
- Lấy ra: đúng kiểu số nguyên mong muốn
- Hỗ trợ: chuyển đổi giữa các kiểu int khác nhau (int32 ↔ int64, …)
- Giới hạn: nếu dữ liệu là float → sẽ cắt phần thập phân
- Ví dụ: 42.7 → 42, "123" → lỗi (string không auto convert sang int)
- KIỂU SỐ NGUYÊN DƯƠNG (uint, uint8, uint16, uint32, uint64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu uint mong muốn
- Hỗ trợ: cross-convert giữa các kiểu uint
- Giới hạn: số âm → gây tràn (overflow)
- KIỂU SỐ THỰC (float32, float64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu float mong muốn
- Hỗ trợ: convert int → float (42 → 42.0)
- Hỗ trợ: cross-convert float32 ↔ float64
- Ví dụ: 42 → 42.0, "42.5" → lỗi (string không auto convert sang float)
- KIỂU BOOLEAN:
- Lưu trong Redis: JSON boolean
- Lấy ra: bool
- Giới hạn: không auto convert từ số hoặc chuỗi
- KIỂU MẢNG (slice):
- Lưu trong Redis: JSON array
- Lấy ra: đúng kiểu slice mong muốn
- Hỗ trợ: []string, []int, []float64, …
- Giới hạn: type mismatch sẽ fail (vd: [1,2,3] → []string sẽ fail)
- KIỂU CẤU TRÚC VÀ MAP (struct/map):
- Lưu trong Redis: JSON object
- Lấy ra: struct hoặc map tương ứng
- Sử dụng json.Unmarshal theo chuẩn Go
Error handling:
- Nếu conversion không hợp lệ → trả về zero-value của T
- Nếu JSON parse lỗi → trả về zero-value
- Nếu key không tồn tại → trả về zero-value
- Nếu lỗi kết nối → log lỗi và trả về zero-value
Performance:
- Với string: không cần unmarshal → nhanh hơn
- Với kiểu primitive: có path convert riêng tối ưu
- Với struct/map phức tạp: dùng json.Unmarshal tiêu chuẩn
Usage:
// Lưu các kiểu dữ liệu khác nhau
Save(client, "int_key", 42) // Lưu: 42
Save(client, "float_key", 42.5) // Lưu: 42.5
Save(client, "string_key", "hello") // Lưu: "hello"
Save(client, "bool_key", true) // Lưu: true
Save(client, "struct_key", User{ID:1,Name:"John"}) // Lưu: {"id":1,"name":"John"}
// Lấy dữ liệu với chuyển đổi kiểu
val1 := Get[string](client, "int_key") // Return: "42"
val2 := Get[float64](client, "int_key") // Return: 42.0
val3 := Get[int](client, "float_key") // Return: 42 (bỏ phần thập phân)
val4 := Get[int](client, "string_key") // Return: 0 (convert lỗi)
val5 := Get[User](client, "struct_key") // Return: User{ID:1, Name:"John"}
// Ví dụ với struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
user := Get[User](client, "struct_key")
fmt.Println(user.Name) // "John"func GetCtx
func GetCtx[T any](client *Client, ctx context.Context, key string) TGetCtx lấy dữ liệu từ Redis theo key và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T), với khả năng chuyển đổi kiểu (type conversion) thông minh.
Hàm này hỗ trợ các trường hợp chuyển đổi giữa dữ liệu JSON lưu trong Redis và các kiểu dữ liệu Go thông dụng.
Các kiểu dữ liệu được hỗ trợ:
- KIỂU CHUỖI (string):
- Lưu trong Redis: Bất kỳ giá trị JSON nào
- Lấy ra: giá trị gốc nếu lưu dạng string, dạng raw nếu lưu kiểu khác
- Ví dụ: "hello" → "hello", 123 → "123", true → "true", {"name":"John"} → `{"name":"John"}`
- KIỂU SỐ NGUYÊN (int, int8, int16, int32, int64):
- Lưu trong Redis: JSON number (int/float)
- Lấy ra: đúng kiểu số nguyên mong muốn
- Hỗ trợ: chuyển đổi giữa các kiểu int khác nhau (int32 ↔ int64, …)
- Giới hạn: nếu dữ liệu là float → sẽ cắt phần thập phân
- Ví dụ: 42.7 → 42, "123" → lỗi (string không auto convert sang int)
- KIỂU SỐ NGUYÊN DƯƠNG (uint, uint8, uint16, uint32, uint64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu uint mong muốn
- Hỗ trợ: cross-convert giữa các kiểu uint
- Giới hạn: số âm → gây tràn (overflow)
- KIỂU SỐ THỰC (float32, float64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu float mong muốn
- Hỗ trợ: convert int → float (42 → 42.0)
- Hỗ trợ: cross-convert float32 ↔ float64
- Ví dụ: 42 → 42.0, "42.5" → lỗi (string không auto convert sang float)
- KIỂU BOOLEAN:
- Lưu trong Redis: JSON boolean
- Lấy ra: bool
- Giới hạn: không auto convert từ số hoặc chuỗi
- KIỂU MẢNG (slice):
- Lưu trong Redis: JSON array
- Lấy ra: đúng kiểu slice mong muốn
- Hỗ trợ: []string, []int, []float64, …
- Giới hạn: type mismatch sẽ fail (vd: [1,2,3] → []string sẽ fail)
- KIỂU CẤU TRÚC VÀ MAP (struct/map):
- Lưu trong Redis: JSON object
- Lấy ra: struct hoặc map tương ứng
- Sử dụng json.Unmarshal theo chuẩn Go
Error handling:
- Nếu conversion không hợp lệ → trả về zero-value của T
- Nếu JSON parse lỗi → trả về zero-value
- Nếu key không tồn tại → trả về zero-value
- Nếu lỗi kết nối → log lỗi và trả về zero-value
Performance:
- Với string: không cần unmarshal → nhanh hơn
- Với kiểu primitive: có path convert riêng tối ưu
- Với struct/map phức tạp: dùng json.Unmarshal tiêu chuẩn
Usage:
// Lưu các kiểu dữ liệu khác nhau
SaveCtx(client, ctx, "int_key", 42) // Lưu: 42
SaveCtx(client, ctx, "float_key", 42.5) // Lưu: 42.5
SaveCtx(client, ctx, "string_key", "hello") // Lưu: "hello"
SaveCtx(client, ctx, "bool_key", true) // Lưu: true
SaveCtx(client, ctx, "struct_key", User{ID:1,Name:"John"}) // Lưu: {"id":1,"name":"John"}
// Lấy dữ liệu với chuyển đổi kiểu
val1 := GetCtx[string](client, ctx, "int_key") // Return: "42"
val2 := GetCtx[float64](client, ctx, "int_key") // Return: 42.0
val3 := GetCtx[int](client, ctx, "float_key") // Return: 42 (bỏ phần thập phân)
val4 := GetCtx[int](client, ctx, "string_key") // Return: 0 (convert lỗi)
val5 := GetCtx[User](client, ctx, "struct_key") // Return: User{ID:1, Name:"John"}
// Ví dụ với struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
user := GetCtx[User](client, ctx, "struct_key")
fmt.Println(user.Name) // "John"func GetExist
func GetExist[T any](client *Client, key string) (T, bool)GetExist lấy dữ liệu từ Redis theo key và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T), với khả năng chuyển đổi kiểu (type conversion) thông minh.
Hàm trả về thêm một giá trị boolean để chỉ ra liệu key có tồn tại trong Redis hay không. Giá trị existed = true nghĩa là key tồn tại (dù giá trị có thể là zero-value của T).
Hàm này hỗ trợ các trường hợp chuyển đổi giữa dữ liệu JSON lưu trong Redis và các kiểu dữ liệu Go thông dụng.
Các kiểu dữ liệu được hỗ trợ:
- KIỂU CHUỖI (string):
- Lưu trong Redis: Bất kỳ giá trị JSON nào
- Lấy ra: giá trị gốc nếu lưu dạng string, dạng raw nếu lưu kiểu khác
- Ví dụ: "hello" → "hello", 123 → "123", true → "true", {"name":"John"} → `{"name":"John"}`
- KIỂU SỐ NGUYÊN (int, int8, int16, int32, int64):
- Lưu trong Redis: JSON number (int/float)
- Lấy ra: đúng kiểu số nguyên mong muốn
- Hỗ trợ: chuyển đổi giữa các kiểu int khác nhau (int32 ↔ int64, …)
- Giới hạn: nếu dữ liệu là float → sẽ cắt phần thập phân
- Ví dụ: 42.7 → 42, "123" → lỗi (string không auto convert sang int)
- KIỂU SỐ NGUYÊN DƯƠNG (uint, uint8, uint16, uint32, uint64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu uint mong muốn
- Hỗ trợ: cross-convert giữa các kiểu uint
- Giới hạn: số âm → gây tràn (overflow)
- KIỂU SỐ THỰC (float32, float64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu float mong muốn
- Hỗ trợ: convert int → float (42 → 42.0)
- Hỗ trợ: cross-convert float32 ↔ float64
- Ví dụ: 42 → 42.0, "42.5" → lỗi (string không auto convert sang float)
- KIỂU BOOLEAN:
- Lưu trong Redis: JSON boolean
- Lấy ra: bool
- Giới hạn: không auto convert từ số hoặc chuỗi
- KIỂU MẢNG (slice):
- Lưu trong Redis: JSON array
- Lấy ra: đúng kiểu slice mong muốn
- Hỗ trợ: []string, []int, []float64, …
- Giới hạn: type mismatch sẽ fail (vd: [1,2,3] → []string sẽ fail)
- KIỂU CẤU TRÚC VÀ MAP (struct/map):
- Lưu trong Redis: JSON object
- Lấy ra: struct hoặc map tương ứng
- Sử dụng json.Unmarshal theo chuẩn Go
Error handling:
- Nếu conversion không hợp lệ → trả về zero-value của T
- Nếu JSON parse lỗi → trả về zero-value
- Nếu key không tồn tại → trả về zero-value
- Nếu lỗi kết nối → log lỗi và trả về zero-value
Performance:
- Với string: không cần unmarshal → nhanh hơn
- Với kiểu primitive: có path convert riêng tối ưu
- Với struct/map phức tạp: dùng json.Unmarshal tiêu chuẩn
Usage:
// Lưu các kiểu dữ liệu khác nhau
Save(client, "int_key", 42) // Lưu: 42
Save(client, "float_key", 42.5) // Lưu: 42.5
Save(client, "string_key", "hello") // Lưu: "hello"
Save(client, "bool_key", true) // Lưu: true
Save(client, "struct_key", User{ID:1,Name:"John"}) // Lưu: {"id":1,"name":"John"}
// Lấy dữ liệu với chuyển đổi kiểu
val1, existed := GetExist[string](client, "int_key") // Return: "42", true
val2, existed := GetExist[float64](client, "int_key") // Return: 42.0, true
val3, existed := GetExist[int](client, "float_key") // Return: 42, true (bỏ phần thập phân)
val4, existed := GetExist[int](client, "string_key") // Return: 0, true (convert lỗi)
val5, existed := GetExist[User](client, "struct_key") // Return: User{ID:1, Name:"John"}, true
// Ví dụ với struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
user, existed := GetExist[User](client, "struct_key")
fmt.Println(user.Name) // "John"func GetExistCtx
func GetExistCtx[T any](client *Client, ctx context.Context, key string) (T, bool)GetExistCtx lấy dữ liệu từ Redis theo key và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T), với khả năng chuyển đổi kiểu (type conversion) thông minh.
Hàm trả về thêm một giá trị boolean để chỉ ra liệu key có tồn tại trong Redis hay không. Giá trị existed = true nghĩa là key tồn tại (dù giá trị có thể là zero-value của T).
Hàm này hỗ trợ các trường hợp chuyển đổi giữa dữ liệu JSON lưu trong Redis và các kiểu dữ liệu Go thông dụng.
Các kiểu dữ liệu được hỗ trợ:
- KIỂU CHUỖI (string):
- Lưu trong Redis: Bất kỳ giá trị JSON nào
- Lấy ra: giá trị gốc nếu lưu dạng string, dạng raw nếu lưu kiểu khác
- Ví dụ: "hello" → "hello", 123 → "123", true → "true", {"name":"John"} → `{"name":"John"}`
- KIỂU SỐ NGUYÊN (int, int8, int16, int32, int64):
- Lưu trong Redis: JSON number (int/float)
- Lấy ra: đúng kiểu số nguyên mong muốn
- Hỗ trợ: chuyển đổi giữa các kiểu int khác nhau (int32 ↔ int64, …)
- Giới hạn: nếu dữ liệu là float → sẽ cắt phần thập phân
- Ví dụ: 42.7 → 42, "123" → lỗi (string không auto convert sang int)
- KIỂU SỐ NGUYÊN DƯƠNG (uint, uint8, uint16, uint32, uint64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu uint mong muốn
- Hỗ trợ: cross-convert giữa các kiểu uint
- Giới hạn: số âm → gây tràn (overflow)
- KIỂU SỐ THỰC (float32, float64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu float mong muốn
- Hỗ trợ: convert int → float (42 → 42.0)
- Hỗ trợ: cross-convert float32 ↔ float64
- Ví dụ: 42 → 42.0, "42.5" → lỗi (string không auto convert sang float)
- KIỂU BOOLEAN:
- Lưu trong Redis: JSON boolean
- Lấy ra: bool
- Giới hạn: không auto convert từ số hoặc chuỗi
- KIỂU MẢNG (slice):
- Lưu trong Redis: JSON array
- Lấy ra: đúng kiểu slice mong muốn
- Hỗ trợ: []string, []int, []float64, …
- Giới hạn: type mismatch sẽ fail (vd: [1,2,3] → []string sẽ fail)
- KIỂU CẤU TRÚC VÀ MAP (struct/map):
- Lưu trong Redis: JSON object
- Lấy ra: struct hoặc map tương ứng
- Sử dụng json.Unmarshal theo chuẩn Go
Error handling:
- Nếu conversion không hợp lệ → trả về zero-value của T
- Nếu JSON parse lỗi → trả về zero-value
- Nếu key không tồn tại → trả về zero-value
- Nếu lỗi kết nối → log lỗi và trả về zero-value
Performance:
- Với string: không cần unmarshal → nhanh hơn
- Với kiểu primitive: có path convert riêng tối ưu
- Với struct/map phức tạp: dùng json.Unmarshal tiêu chuẩn
Usage:
// Lưu các kiểu dữ liệu khác nhau
SaveCtx(client, ctx, "int_key", 42) // Lưu: 42
SaveCtx(client, ctx, "float_key", 42.5) // Lưu: 42.5
SaveCtx(client, ctx, "string_key", "hello") // Lưu: "hello"
SaveCtx(client, ctx, "bool_key", true) // Lưu: true
SaveCtx(client, ctx, "struct_key", User{ID:1,Name:"John"}) // Lưu: {"id":1,"name":"John"}
// Lấy dữ liệu với chuyển đổi kiểu
val1, existed := GetExistCtx[string](client, ctx, "int_key") // Return: "42", true
val2, existed := GetExistCtx[float64](client, ctx, "int_key") // Return: 42.0, true
val3, existed := GetExistCtx[int](client, ctx, "float_key") // Return: 42, true (bỏ phần thập phân)
val4, existed := GetExistCtx[int](client, ctx, "string_key") // Return: 0, true (convert lỗi)
val5, existed := GetExistCtx[User](client, ctx, "struct_key") // Return: User{ID:1, Name:"John"}, true
// Ví dụ với struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
user, existed := GetExistCtx[User](client, ctx, "struct_key")
fmt.Println(user.Name) // "John"func GetHashFieldSet
func GetHashFieldSet[T any](client *Client, key string, args any) TGetHashFieldSet lấy dữ liệu từ Redis hash field và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T). Hàm này tương ứng với SaveHashFieldSet và sử dụng context mặc định.
Parameters:
- client: Redis client instance
- key: Redis hash key
- args: Tham số để tạo field name (sử dụng CreatePageListDataKey)
Return:
- T: Dữ liệu đã deserialize với kiểu T, hoặc zero-value nếu không tìm thấy hoặc lỗi
Usage:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Lưu dữ liệu
SaveHashFieldSet(client, "users:cache", User{ID: 1, Name: "John"}, "user:1")
// Lấy dữ liệu
user := GetHashFieldSet[User](client, "users:cache", "user:1")
fmt.Println(user.Name) // "John"func GetHashFieldSetCtx
func GetHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, args any) TGetHashFieldSetCtx lấy dữ liệu từ Redis hash field và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T), với khả năng chuyển đổi kiểu (type conversion) thông minh và sử dụng custom context.
Hàm này tương ứng với SaveHashFieldSetCtx và SaveHashFieldSetTTLCtx.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- key: Redis hash key
- args: Tham số để tạo field name (sử dụng CreatePageListDataKey)
Return:
- T: Dữ liệu đã deserialize với kiểu T, hoặc zero-value nếu không tìm thấy hoặc lỗi
Các kiểu dữ liệu được hỗ trợ:
- KIỂU CHUỖI (string):
- Lưu trong Redis: Bất kỳ giá trị JSON nào
- Lấy ra: string (dạng JSON gốc)
- KIỂU SỐ NGUYÊN (int, int8, int16, int32, int64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu số nguyên mong muốn
- Hỗ trợ: chuyển đổi giữa các kiểu int khác nhau
- KIỂU SỐ NGUYÊN DƯƠNG (uint, uint8, uint16, uint32, uint64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu uint mong muốn
- Hỗ trợ: cross-convert giữa các kiểu uint
- KIỂU SỐ THỰC (float32, float64):
- Lưu trong Redis: JSON number
- Lấy ra: đúng kiểu float mong muốn
- Hỗ trợ: convert int → float (42 → 42.0)
- KIỂU BOOLEAN (bool):
- Lưu trong Redis: JSON boolean
- Lấy ra: bool
- KIỂU MẢNG (slice):
- Lưu trong Redis: JSON array
- Lấy ra: đúng kiểu slice mong muốn
- Hỗ trợ: []string, []int, []float64, …
- KIỂU CẤU TRÚC VÀ MAP (struct/map):
- Lưu trong Redis: JSON object
- Lấy ra: struct hoặc map tương ứng
- Sử dụng json.Unmarshal theo chuẩn Go
Error handling:
- Nếu key hoặc field không tồn tại → trả về zero-value
- Nếu JSON deserialization lỗi → trả về zero-value
- Nếu lỗi kết nối hoặc Redis operation → log lỗi và trả về zero-value
Performance:
- Với string: không cần unmarshal → nhanh hơn
- Với kiểu primitive: có path convert riêng tối ưu
- Với struct/map phức tạp: dùng json.Unmarshal tiêu chuẩn
Usage:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
// Lưu dữ liệu với context
SaveHashFieldSetCtx(client, ctx, "users:cache", User{ID: 1, Name: "John", Age: 30}, "user:1")
// Lấy dữ liệu với context
user := GetHashFieldSetCtx[User](client, ctx, "users:cache", "user:1")
fmt.Println(user.Name) // "John"
// Lấy các kiểu primitive
count := GetHashFieldSetCtx[int](client, ctx, "stats:cache", "user:1:count")
name := GetHashFieldSetCtx[string](client, ctx, "names:cache", "user:1")func GetRef
func GetRef[T any](client *Client, key string) TGetRefCtx sẽ lấy một giá trị từ Redis theo key tham chiếu và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T); Hàm này sử dụng cùng với SaveSetKeysRef và SaveSetKeysRefCtx
func GetRefCtx
func GetRefCtx[T any](client *Client, ctx context.Context, key string) TGetRefCtx sẽ lấy một giá trị từ Redis theo key tham chiếu và ánh xạ sang kiểu dữ liệu Go bất kỳ (generic T); Hàm này sử dụng cùng với SaveSetKeysRef và SaveSetKeysRefCtx
func GetsByIDs
func GetsByIDs[T any](client *Client, keyFn func(string) string, ids ...string) []Tfunc GetsByIDsCtx
func GetsByIDsCtx[T any](client *Client, ctx context.Context, keyFn func(string) string, ids ...string) []TGetsByIDsCtx retrieves multiple values from Redis by IDs using custom context
func GetsListPage
func GetsListPage[T any](client *Client, hashKey string, args ...any) ([]T, int)GetsListPage retrieves a list of data and total count from a Redis hash.
func GetsListPageCtx
func GetsListPageCtx[T any](client *Client, ctx context.Context, hashKey string, args ...any) ([]T, int)GetsListPageCtx retrieves a list of data and total count from a Redis hash using custom context
func IncrementWindowCounterValid
func IncrementWindowCounterValid(client *Client, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64IncrementWindowCounterValid tăng một bộ đếm trong một cửa sổ thời gian (time window) cho một đối tượng cụ thể và kiểm tra xem bộ đếm có vượt quá giới hạn tối đa không.
Parameters:
- client (*Client): Kết nối đến Redis
- windowSlideSize (int32): Kích thước của cửa sổ thời gian (tính bằng giây)
- windowSlideInterval (int32): Khoảng thời gian trượt giữa các cửa sổ (tính bằng giây)
- windowMaxCounter (int32): Giới hạn tối đa của bộ đếm trong cửa sổ
- count (int32): Giá trị bộ đếm cần tăng
- args (...any): Các tham số bổ sung để tạo key cho Redis;
args có thể là một danh sách các đối tượng như sau:
- args[0]: projectID (string): ID của dự án
- args[1]: subjectType (string): Loại đối tượng (ví dụ: "user", "post")
- args[2]: subjectID (string): ID của đối tượng cụ thể
- args[3]: userIdentifier (string): Định danh của user (e.g., IP address)
Returns:
- currentCount (int64): lớn hơn 0 nếu tăng thành công và chưa vượt quá giới hạn, -1 nếu không tăng được hoặc đã vượt giới hạn, cần chờ reset window.
Notes:
- Nếu windowMaxCounter hoặc windowSlideSize bằng 0, hàm luôn trả về true
- Nếu windowSlideInterval bằng 0, nó sẽ được gán bằng windowSlideSize
- Hàm sử dụng Redis với Lua script để đảm bảo tính atomic của thao tác
func IncrementWindowCounterValidCtx
func IncrementWindowCounterValidCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64IncrementWindowCounterValid tăng một bộ đếm trong một cửa sổ thời gian (time window) cho một đối tượng cụ thể và kiểm tra xem bộ đếm có vượt quá giới hạn tối đa không.
Parameters:
- client (*Client): Kết nối đến Redis
- ctx (context.Context): Ngữ cảnh để quản lý thời gian chờ và hủy bỏ
- windowSlideSize (int32): Kích thước của cửa sổ thời gian (tính bằng giây)
- windowSlideInterval (int32): Khoảng thời gian trượt giữa các cửa sổ (tính bằng giây)
- windowMaxCounter (int32): Giới hạn tối đa của bộ đếm trong cửa sổ
- count (int32): Giá trị bộ đếm cần tăng
- args (...any): Các tham số bổ sung để tạo key cho Redis;
args có thể là một danh sách các đối tượng như sau:
- args[0]: projectID (string): ID của dự án
- args[1]: subjectType (string): Loại đối tượng (ví dụ: "user", "post")
- args[2]: subjectID (string): ID của đối tượng cụ thể
- args[3]: userIdentifier (string): Định danh của user (e.g., IP address)
Returns:
- currentCount (int64): lớn hơn 0 nếu tăng thành công và chưa vượt quá giới hạn, -1 nếu không tăng được hoặc đã vượt giới hạn, cần chờ reset window.
Notes:
- Nếu windowMaxCounter hoặc windowSlideSize bằng 0, hàm luôn trả về true
- Nếu windowSlideInterval bằng 0, nó sẽ được gán bằng windowSlideSize
- Hàm sử dụng Redis với Lua script để đảm bảo tính atomic của thao tác
func IncrementWindowCounterValidWithCountCtx
func IncrementWindowCounterValidWithCountCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter, count int32, args ...any) int64IncrementWindowCounterValidWithCount tăng một bộ đếm trong một cửa sổ thời gian (time window) cho một đối tượng cụ thể và kiểm tra xem bộ đếm có vượt quá giới hạn tối đa không, yêu cầu truyền count
Parameters:
- client (*Client): Kết nối đến Redis
- windowSlideSize (int32): Kích thước của cửa sổ thời gian (tính bằng giây)
- windowSlideInterval (int32): Khoảng thời gian trượt giữa các cửa sổ (tính bằng giây)
- windowMaxCounter (int32): Giới hạn tối đa của bộ đếm trong cửa sổ
- count (int32): Giá trị bộ đếm cần tăng
- args (...any): Các tham số bổ sung để tạo key cho Redis;
args có thể là một danh sách các đối tượng như sau:
- args[0]: projectID (string): ID của dự án
- args[1]: subjectType (string): Loại đối tượng (ví dụ: "user", "post")
- args[2]: subjectID (string): ID của đối tượng cụ thể
- args[3]: userIdentifier (string): Định danh của user (e.g., IP address)
Returns:
- currentCount (int64): lớn hơn 0 nếu tăng thành công và chưa vượt quá giới hạn, -1 nếu không tăng được hoặc đã vượt giới hạn, cần chờ reset window.
Notes:
- Nếu windowMaxCounter hoặc windowSlideSize bằng 0, hàm luôn trả về true
- Nếu windowSlideInterval bằng 0, nó sẽ được gán bằng windowSlideSize
- Hàm sử dụng Redis với Lua script để đảm bảo tính atomic của thao tác
func ResetWindowCounter
func ResetWindowCounter(client *Client, windowSlideInterval int32, args ...any) errorResetWindowCounter xóa bộ đếm trong một cửa sổ thời gian (time window) cho một đối tượng cụ thể, thường được gọi khi cửa sổ thời gian kết thúc để reset lại bộ đếm về 0.
Parameters:
- client (*Client): Kết nối đến Redis
- windowSlideInterval (int32): Khoảng thời gian trượt giữa các cửa sổ (tính bằng giây)
- args (...any): Các tham số bổ sung để tạo key cho Redis;
args có thể là một danh sách các đối tượng như sau:
- args[0]: projectID (string): ID của dự án
- args[1]: subjectType (string): Loại đối tượng (ví dụ: "user", "post")
- args[2]: subjectID (string): ID của đối tượng cụ thể
- args[3]: userIdentifier (string): Định danh của user (e.g., IP address)
Returns:
- error: lỗi nếu có, nil nếu thành công
func Save
func Save(client *Client, key string, expiration time.Duration, md any) errorSave stores a single value in Redis with a specified key and expiration
func SaveCtx
func SaveCtx(client *Client, ctx context.Context, key string, expiration time.Duration, md any) errorSaveCtx stores a single value in Redis with comprehensive type support and JSON serialization.
This function accepts any Go type and stores it in Redis as a JSON string. All Go types are serialized using JSON encoding, which ensures consistent storage format and enables type conversion during retrieval with GetCtx.
Supported Storage Types:
- PRIMITIVE TYPES:
- Integers: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64 Stored as: JSON numbers (e.g., 42)
- Floats: float32, float64 Stored as: JSON numbers (e.g., 42.5)
- Booleans: bool Stored as: JSON booleans (true/false)
- Strings: string Stored as: JSON strings (e.g., "hello")
- COMPLEX TYPES:
- Slices/Arrays: []T, [N]T Stored as: JSON arrays (e.g., [1,2,3] or ["a","b","c"])
- Maps: map[K]V Stored as: JSON objects (e.g., {"key":"value"})
- Structs: struct{...} Stored as: JSON objects (e.g., {"field1":"value1","field2":value2})
- Pointers: *T Stored as: JSON representation of the pointed value (nil → null)
- SPECIAL CASES:
- Interfaces: interface{...} Stored as: JSON representation of the concrete type
- Custom types with json tags Stored as: Respects json:"..." tags for field naming and omission
- time.Time and similar types Stored as: JSON string representation
Storage Format Examples:
SaveCtx(client, ctx, "int_key", 1*time.Hour, 42) // Stores: 42
SaveCtx(client, ctx, "float_key", 1*time.Hour, 42.5) // Stores: 42.5
SaveCtx(client, ctx, "string_key", 1*time.Hour, "hello") // Stores: "hello"
SaveCtx(client, ctx, "bool_key", 1*time.Hour, true) // Stores: true
SaveCtx(client, ctx, "slice_key", 1*time.Hour, []int{1,2,3}) // Stores: [1,2,3]
SaveCtx(client, ctx, "map_key", 1*time.Hour, map[string]int{"a":1}) // Stores: {"a":1}
SaveCtx(client, ctx, "struct_key", 1*time.Hour, User{Name:"John", Age:30}) // Stores: {"name":"John","age":30}
SaveCtx(client, ctx, "nil_key", 1*time.Hour, (*User)(nil)) // Stores: nullRetrieval Compatibility:
After saving with SaveCtx, data can be retrieved using GetCtx with:
- Same type: Perfect match retrieval
- Compatible types: Automatic conversion (see GetCtx documentation)
- string type: Always works (returns JSON representation)Error Handling:
- Returns error if Redis connection fails
- Returns error if Redis SET operation fails
- JSON serialization errors are handled internally by fson.JSONString
Performance Notes:
- Uses fson.JSONString for optimized JSON serialization
- Efficient for all Go types including large structs and slices
- Memory-efficient serialization without intermediate allocations
Parameters:
- client: Redis client instance
- ctx: Context for timeout and cancellation control
- key: Redis key for storage (must be non-empty)
- expiration: TTL for the key (use 0 for no expiration)
- md: Any Go value to store (can be nil)
Usage Examples:
// Save primitive types
SaveCtx(client, ctx, "user_id", 24*time.Hour, 12345)
SaveCtx(client, ctx, "user_score", 1*time.Hour, 95.7)
SaveCtx(client, ctx, "user_active", 30*time.Minute, true)
SaveCtx(client, ctx, "user_name", 24*time.Hour, "John Doe")
// Save complex types
user := User{ID: "123", Name: "John", Age: 30}
SaveCtx(client, ctx, "user:123", 24*time.Hour, user)
tags := []string{"golang", "redis", "json"}
SaveCtx(client, ctx, "user:123:tags", 1*time.Hour, tags)
metadata := map[string]any{
"created_at": time.Now(),
"version": 2,
"features": []string{"premium", "analytics"},
}
SaveCtx(client, ctx, "user:123:metadata", 6*time.Hour, metadata)func SaveHashFieldSet
func SaveHashFieldSet[T any](client *Client, key string, data T, args any) errorSaveHashFieldSet lưu dữ liệu vào một field của Redis hash với TTL mặc định. Hàm này sử dụng context mặc định và TTL: key = 24h, field = 1h.
Parameters:
- client: Redis client instance
- key: Redis hash key
- data: Dữ liệu bất kỳ kiểu T để lưu (sẽ serialize sang JSON)
- args: Tham số để tạo field name (sử dụng CreatePageListDataKey)
Return:
- error: Trả về lỗi nếu kết nối thất bại hoặc Redis operation thất bại
Usage:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Lưu user vào hash field
user := User{ID: 1, Name: "John"}
err := SaveHashFieldSet(client, "users:cache", user, "user:1")
// Lấy lại dữ liệu
retrievedUser := GetHashFieldSet[User](client, "users:cache", "user:1")func SaveHashFieldSetCtx
func SaveHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, data T, args any) errorSaveHashFieldSetCtx lưu dữ liệu vào một field của Redis hash với context tùy chỉnh và TTL mặc định. TTL mặc định: key = 24 giờ, field = 1 giờ.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- key: Redis hash key
- data: Dữ liệu bất kỳ kiểu T để lưu (sẽ serialize sang JSON)
- args: Tham số để tạo field name (sử dụng CreatePageListDataKey)
Return:
- error: Trả về lỗi nếu kết nối thất bại hoặc Redis operation thất bại
Usage:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
user := User{ID: 1, Name: "John", Age: 30}
err := SaveHashFieldSetCtx(client, ctx, "users:cache", user, "user:1")func SaveHashFieldSetTTL
func SaveHashFieldSetTTL[T any](client *Client, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) errorSaveHashFieldSetTTL lưu dữ liệu vào một field của Redis hash với TTL tùy chỉnh. Hàm này sử dụng context mặc định và cho phép đặt TTL cho cả key và field.
Note: Hàm này có lỗi logic - nó tạo context mới trong khi đã nhận context từ parameter. Nên sử dụng SaveHashFieldSetTTLCtx trực tiếp thay vì hàm này.
Parameters:
- client: Redis client instance
- key: Redis hash key
- keyTTL: Thời gian sống của hash key (sử dụng 0 để không set TTL)
- fieldTTL: Thời gian sống của field (sử dụng 0 để không set TTL)
- data: Dữ liệu bất kỳ kiểu T để lưu
- args: Tham số để tạo field name
Return:
- error: Trả về lỗi nếu Redis operation thất bại
func SaveHashFieldSetTTLCtx
func SaveHashFieldSetTTLCtx[T any](client *Client, ctx context.Context, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) errorSaveHashFieldSetTTLCtx lưu dữ liệu vào một field của Redis hash với context và TTL tùy chỉnh. Đây là hàm core implementation cho các hàm SaveHashField* khác.
Parameters:
- client: Redis client instance
- ctx: Context để kiểm soát timeout và cancellation
- key: Redis hash key
- keyTTL: Thời gian sống của hash key (0 = không set TTL cho key)
- fieldTTL: Thời gian sống của field (0 = không set TTL cho field)
- data: Dữ liệu bất kỳ kiểu T để lưu (sẽ serialize sang JSON)
- args: Tham số để tạo field name (sử dụng CreatePageListDataKey)
Return:
- error: Trả về lỗi nếu kết nối thất bại hoặc Redis operation thất bại
Flow:
- Lưu dữ liệu vào hash field bằng lệnh HSET
- Nếu keyTTL > 0: đặt TTL cho toàn bộ hash key bằng lệnh EXPIRE
- Nếu fieldTTL > 0: đặt TTL cho riêng field bằng lệnh HEXPIRE
Note:
- keyTTL áp dụng cho toàn bộ hash key
- fieldTTL chỉ áp dụng cho field cụ thể đang lưu
- Nếu field đã tồn tại, dữ liệu cũ sẽ bị ghi đè
Usage:
ctx := context.Background()
user := User{ID: 1, Name: "John"}
// Lưu với TTL tùy chỉnh: key = 12h, field = 30 phút
err := SaveHashFieldSetTTLCtx(client, ctx, "users:cache",
12*time.Hour, 30*time.Minute, user, "user:1")
// Lưu không TTL cho key, chỉ set TTL cho field
err = SaveHashFieldSetTTLCtx(client, ctx, "users:cache",
0, 1*time.Hour, user, "user:2")func SaveListPage
func SaveListPage[T any](client *Client, hashKey string, data []T, total int, args ...any) errorSaveListPage saves a list of data and total count to a Redis hash.
func SaveListPageCtx
func SaveListPageCtx[T any](client *Client, ctx context.Context, hashKey string, data []T, total int, args ...any) errorSaveListPageCtx saves a list of data and total count to a Redis hash using custom context
func SaveSet
func SaveSet[T IDer](client *Client, keyFn func(string) string, expiration time.Duration, mds ...*T) errorSaveSet stores multiple IDer objects in Redis with keys generated by keyFn
func SaveSetCtx
func SaveSetCtx[T IDer](client *Client, ctx context.Context, keyFn func(string) string, expiration time.Duration, mds ...*T) errorSaveSetCtx stores multiple IDer objects in Redis with keys generated by keyFn using custom context
func SaveSetKeys
func SaveSetKeys(client *Client, md any, expiration time.Duration, keys ...string) errorSaveSetKeysCtx sẽ lưu một đối tượng vào ĐỒNG THỜI nhiều khóa Redis; Hàm này khác với hàm SaveSetKeysRefCtx;
func SaveSetKeysCtx
func SaveSetKeysCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) errorSaveSetKeysCtx sẽ lưu một đối tượng vào ĐỒNG THỜI nhiều khóa Redis; Hàm này khác với hàm SaveSetKeysRefCtx
func SaveSetKeysRef
func SaveSetKeysRef(client *Client, md any, expiration time.Duration, keys ...string) errorSaveSetKeysRefCtx sẽ lưu một đối tượng vào nhiều khóa Redis, với các khóa sau THAM CHIẾU đến khóa đầu tiên; Hàm này khác với hàm SaveSetKeysCtx; Sử dụng GetRef hoặc GetRefCtx để lấy dữ liệu từ key THAM CHIẾU.
func SaveSetKeysRefCtx
func SaveSetKeysRefCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) errorSaveSetKeysRefCtx sẽ lưu một đối tượng vào nhiều khóa Redis, với các khóa sau THAM CHIẾU đến khóa đầu tiên; Hàm này khác với hàm SaveSetKeysCtx; Sử dụng GetRef hoặc GetRefCtx để lấy dữ liệu từ key THAM CHIẾU.
func SaveSets
func SaveSets[T IDer](client *Client, keyFns []func(string) string, expiration time.Duration, mds ...*T) errorSaveSets stores multiple IDer objects in Redis with multiple key functions
func SaveSetsCtx
func SaveSetsCtx[T IDer](client *Client, ctx context.Context, keyFns []func(string) string, expiration time.Duration, mds ...*T) errorSaveSetsCtx stores multiple IDer objects in Redis with multiple key functions using custom context
func WithAccessInterceptor
func WithAccessInterceptor(enable bool) lib_3rd.Option[config]func WithAccessInterceptorReq
func WithAccessInterceptorReq(enable bool) lib_3rd.Option[config]func WithAccessInterceptorRes
func WithAccessInterceptorRes(enable bool) lib_3rd.Option[config]func WithAddrs
func WithAddrs(addrs ...string) lib_3rd.Option[config]WithAddrs set addresses with host:port format
func WithConfig
func WithConfig(conf *config) lib_3rd.Option[config]func WithDBNum
func WithDBNum(num int) lib_3rd.Option[config]func WithDebugMode
func WithDebugMode(enable bool) lib_3rd.Option[config]func WithEnvironment
func WithEnvironment(env string) lib_3rd.Option[config]func WithLogger
func WithLogger(logger ...flog.FlogInf) lib_3rd.Option[config]func WithMasterName
func WithMasterName(name string) lib_3rd.Option[config]func WithMaxActiveConns
func WithMaxActiveConns(max int) lib_3rd.Option[config]func WithMaxIdleConns
func WithMaxIdleConns(max int) lib_3rd.Option[config]func WithMaxRetries
func WithMaxRetries(max int) lib_3rd.Option[config]func WithMetricInterceptor
func WithMetricInterceptor(enable bool) lib_3rd.Option[config]func WithMinIdleConns
func WithMinIdleConns(min int) lib_3rd.Option[config]func WithName
func WithName(name string) lib_3rd.Option[config]func WithOnFail
func WithOnFail(onFail string) lib_3rd.Option[config]func WithPassword
func WithPassword(password string) lib_3rd.Option[config]WithPassword set password
func WithPoolSize
func WithPoolSize(size int) lib_3rd.Option[config]func WithPoolTimeout
func WithPoolTimeout(timeout time.Duration) lib_3rd.Option[config]func WithReadOnlyMode
func WithReadOnlyMode(enable bool) lib_3rd.Option[config]func WithReadTimeout
func WithReadTimeout(timeout time.Duration) lib_3rd.Option[config]func WithSlowLogThreshold
func WithSlowLogThreshold(threshold time.Duration) lib_3rd.Option[config]func WithStatServerName
func WithStatServerName(name string) lib_3rd.Option[config]func WithTraceInterceptor
func WithTraceInterceptor(enable bool) lib_3rd.Option[config]func WithWriteTimeout
func WithWriteTimeout(timeout time.Duration) lib_3rd.Option[config]type Client
Client đại diện cho client redis sử dụng thư viện rueidis.
type Client struct {
// contains filtered or unexported fields
}func (*Client) Client
func (c *Client) Client() rueidis.Clientfunc (*Client) ClientBloomFilter
func (c *Client) ClientBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64, opts ...rueidisprob.BloomFilterOptionFunc) (rueidisprob.BloomFilter, error)It is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. False positive matches are possible, NewBloomFilter("bloom_filter", 1000, 0.01)
func (*Client) ClientCompact
func (c *Client) ClientCompact() rueidiscompat.CmdableUsing like go-redis
func (*Client) ClientCountingBloomFilter
func (c *Client) ClientCountingBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64) (rueidisprob.CountingBloomFilter, error)Đây là một biến thể của bộ lọc Bloom tiêu chuẩn, bổ sung cơ chế đếm cho mỗi phần tử. Điều này cho phép bộ lọc đếm số lần một phần tử được thêm vào bộ lọc. Đồng thời, nó cũng cho phép loại bỏ các phần tử khỏi bộ lọc. ClientCountingBloomFilter("counting_bloom_filter", 1000, 0.01)
func (*Client) ClientNewSlidingBloomFilter
func (c *Client) ClientNewSlidingBloomFilter(name string, expectedNumberOfItems uint, falsePositiveRate float64, windowSize time.Duration, opts ...rueidisprob.SlidingBloomFilterOptionFunc) (rueidisprob.BloomFilter, error)Đây là một biến thể của bộ lọc Bloom tiêu chuẩn, bổ sung cơ chế cửa sổ trượt. Hữu ích cho các trường hợp bạn cần theo dõi các mục trong một khoảng thời gian nhất định. ClientNewSlidingBloomFilter("sliding_bloom_filter", 1000, 0.01, time.Minute)
func (*Client) Close
func (c *Client) Close() errorClose đóng kết nối redis.
func (*Client) Connection
func (c *Client) Connection() rueidis.ClientConnection trả về client rueidis được sử dụng bên trong.
func (*Client) Liveness
func (c *Client) Liveness() boolLiveness trả về true khi dịch vụ Redis được xem là “sống”
func (*Client) LockClient
func (c *Client) LockClient() *lockClientLockClient trả về distributed lock client.
func (*Client) Logger
func (c *Client) Logger() flog.FlogInfLogger trả về logger của client.
func (*Client) Readiness
func (c *Client) Readiness() boolReadiness trả về true khi dịch vụ Redis sẵn sàng phục vụ
type Err
type Err stringfunc (Err) Error
func (e Err) Error() stringtype IDer
type IDer interface {
GetID() string
}type Lock
Lock represents an obtained, distributed Lock.
type Lock struct {
// contains filtered or unexported fields
}func (*Lock) Key
func (l *Lock) Key() stringKey returns the redis key used by the Lock.
func (*Lock) Metadata
func (l *Lock) Metadata() stringMetadata returns the metadata of the Lock.
func (*Lock) Refresh
func (l *Lock) Refresh(ctx context.Context, ttl time.Duration, opts ...LockOption) errorRefresh extends the Lock with a new TTL. May return ErrNotObtained if refresh is unsuccessful.
func (*Lock) Release
func (l *Lock) Release(ctx context.Context) errorRelease manually releases the Lock. May return ErrLockNotHeld.
func (*Lock) TTL
func (l *Lock) TTL(ctx context.Context) (time.Duration, error)TTL returns the remaining time-to-live. Returns 0 if the Lock has expired.
func (*Lock) Token
func (l *Lock) Token() stringToken returns the token value set by the Lock (giả sử token có độ dài cố định).
type LockOption
LockOption định nghĩa kiểu hàm để cấu hình các tham số của Lock.
type LockOption func(c *lockOption)func WithLockOptionMetadata
func WithLockOptionMetadata(md string) LockOptionWithLockOptionMetadata thêm metadata vào Lock.
func WithLockOptionRetryStrategy
func WithLockOptionRetryStrategy(retryStrategy RetryStrategy) LockOptionWithLockOptionRetryStrategy thêm retry strategy vào Lock.
type PoolStats
PoolStats là cấu trúc chứa số liệu của pool connection. Đây chỉ là ví dụ; bạn cần tự cập nhật các thông số theo cơ chế theo dõi của bạn.
type PoolStats struct {
Hits int64
Misses int64
Timeouts int64
TotalConns int64
IdleConns int64
StaleConns int64
}type RetryStrategy
RetryStrategy allows to customize the Lock retry strategy.
type RetryStrategy interface {
// NextBackOff returns the next backOff duration.
NextBackOff() time.Duration
}func LockOptionExponentialBackOffRetry
func LockOptionExponentialBackOffRetry(min, max time.Duration) RetryStrategyLockOptionExponentialBackOffRetry strategy is an optimization strategy with a retry time of 2**n milliseconds (n means number of times). You can set a minimum and maximum value, the recommended minimum value is not less than 16ms.
func LockOptionLimitRetry
func LockOptionLimitRetry(s RetryStrategy, max int) RetryStrategyLockOptionLimitRetry limits the number of retries to max attempts.
func LockOptionLinearBackOffRetry
func LockOptionLinearBackOffRetry(backOff time.Duration) RetryStrategyLockOptionLinearBackOffRetry allows retries regularly with customized intervals
func LockOptionNoRetry
func LockOptionNoRetry() RetryStrategy--------------------------------No Retry----------------------------------- LockOptionNoRetry acquire the Lock only once.
Generated by gomarkdoc