Skip to content

Import path: gitlab.soludian.com/soludian/fountain/libs/stored/fedis

fedis

go
import "gitlab.soludian.com/soludian/fountain/libs/stored/fedis"

Index

Constants

go
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"
)

go
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")
)

go
const KPackageName = "fedis"

Variables

go
var GetFountainInstance = Lib.GetFountainInstance

go
var GetFountainManager = Lib.GetFountainManager

Sử 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()
go
var InstallFountainInstance = Lib.InstallFountainInstance

Sử 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()
go
var InstallFountainInstanceOnce = Lib.InstallFountainInstanceOnce

Sử 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()
go
var InstallFountainInstances = Lib.InstallFountainInstances

Truy cập thẳng tới bộ quản lý thư viện

go
var Lib = lib_3rd.NewLib(newClient, lib_3rd.WithDefaultConfigsFunc[config, Client](DefaultConfigs), lib_3rd.WithStatsCollectors[config, Client](statsCollector))

go
var WithConfigKey = Lib.WithConfigKey

func AddAddrs

go
func AddAddrs(addrs ...string) lib_3rd.Option[config]

WithAddrs set addresses with host:port format

func CreateCtx

go
func CreateCtx(ctx context.Context) (context.Context, context.CancelFunc)

Check ctx, create new context timeout if parent context have deadline

func CreateDefaultCtx

go
func CreateDefaultCtx() (context.Context, context.CancelFunc)

func CreateDeletePattern

go
func CreateDeletePattern(client *Client, ctx context.Context, pattern string, batchSize ...int64) []rueidis.Completed

CreateDeletePattern 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:

  1. Sử dụng SCAN để iterate qua tất cả keys trong Redis
  2. Với mỗi iteration, lọc keys khớp với pattern
  3. Build UNLINK command cho từng key tìm thấy
  4. 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

go
func CreatePageListDataKey(args any) (string, string)

Return field hash key and field total key

func CreateStatWindowKey

go
func CreateStatWindowKey(windowStartTime int32, args any) string

func Delete

go
func Delete(client *Client, keyFn func(string) string, ids ...string) error

Delete 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

go
func DeleteCtx(client *Client, ctx context.Context, keyFn func(string) string, ids ...string) error

DeleteCtx 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

go
func Deletes(client *Client, keys ...string) error

Deletes 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

go
func DeletesCtx(client *Client, ctx context.Context, keys ...string) error

DeletesCtx 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

go
func Get[T any](client *Client, key string) T

Get 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ợ:

  1. 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"}`
  1. 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)
  1. 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)
  1. 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)
  1. 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
  1. 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)
  1. 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

go
func GetCtx[T any](client *Client, ctx context.Context, key string) T

GetCtx 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ợ:

  1. 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"}`
  1. 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)
  1. 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)
  1. 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)
  1. 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
  1. 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)
  1. 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

go
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ợ:

  1. 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"}`
  1. 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)
  1. 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)
  1. 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)
  1. 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
  1. 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)
  1. 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

go
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ợ:

  1. 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"}`
  1. 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)
  1. 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)
  1. 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)
  1. 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
  1. 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)
  1. 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

go
func GetHashFieldSet[T any](client *Client, key string, args any) T

GetHashFieldSet 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

go
func GetHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, args any) T

GetHashFieldSetCtx 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ợ:

  1. 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)
  1. 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
  1. 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
  1. 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)
  1. KIỂU BOOLEAN (bool):
  • Lưu trong Redis: JSON boolean
  • Lấy ra: bool
  1. 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, …
  1. 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

go
func GetRef[T any](client *Client, key string) T

GetRefCtx 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

go
func GetRefCtx[T any](client *Client, ctx context.Context, key string) T

GetRefCtx 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

go
func GetsByIDs[T any](client *Client, keyFn func(string) string, ids ...string) []T

func GetsByIDsCtx

go
func GetsByIDsCtx[T any](client *Client, ctx context.Context, keyFn func(string) string, ids ...string) []T

GetsByIDsCtx retrieves multiple values from Redis by IDs using custom context

func GetsListPage

go
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

go
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

go
func IncrementWindowCounterValid(client *Client, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64

IncrementWindowCounterValid 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

go
func IncrementWindowCounterValidCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter int32, args ...any) int64

IncrementWindowCounterValid 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

go
func IncrementWindowCounterValidWithCountCtx(client *Client, ctx context.Context, windowSlideSize, windowSlideInterval, windowMaxCounter, count int32, args ...any) int64

IncrementWindowCounterValidWithCount 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

go
func ResetWindowCounter(client *Client, windowSlideInterval int32, args ...any) error

ResetWindowCounter 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

go
func Save(client *Client, key string, expiration time.Duration, md any) error

Save stores a single value in Redis with a specified key and expiration

func SaveCtx

go
func SaveCtx(client *Client, ctx context.Context, key string, expiration time.Duration, md any) error

SaveCtx 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:

  1. 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")
  1. 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)
  1. 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: null

Retrieval 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

go
func SaveHashFieldSet[T any](client *Client, key string, data T, args any) error

SaveHashFieldSet 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

go
func SaveHashFieldSetCtx[T any](client *Client, ctx context.Context, key string, data T, args any) error

SaveHashFieldSetCtx 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

go
func SaveHashFieldSetTTL[T any](client *Client, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) error

SaveHashFieldSetTTL 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

go
func SaveHashFieldSetTTLCtx[T any](client *Client, ctx context.Context, key string, keyTTL time.Duration, fieldTTL time.Duration, data T, args any) error

SaveHashFieldSetTTLCtx 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:

  1. Lưu dữ liệu vào hash field bằng lệnh HSET
  2. Nếu keyTTL > 0: đặt TTL cho toàn bộ hash key bằng lệnh EXPIRE
  3. 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

go
func SaveListPage[T any](client *Client, hashKey string, data []T, total int, args ...any) error

SaveListPage saves a list of data and total count to a Redis hash.

func SaveListPageCtx

go
func SaveListPageCtx[T any](client *Client, ctx context.Context, hashKey string, data []T, total int, args ...any) error

SaveListPageCtx saves a list of data and total count to a Redis hash using custom context

func SaveSet

go
func SaveSet[T IDer](client *Client, keyFn func(string) string, expiration time.Duration, mds ...*T) error

SaveSet stores multiple IDer objects in Redis with keys generated by keyFn

func SaveSetCtx

go
func SaveSetCtx[T IDer](client *Client, ctx context.Context, keyFn func(string) string, expiration time.Duration, mds ...*T) error

SaveSetCtx stores multiple IDer objects in Redis with keys generated by keyFn using custom context

func SaveSetKeys

go
func SaveSetKeys(client *Client, md any, expiration time.Duration, keys ...string) error

SaveSetKeysCtx 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

go
func SaveSetKeysCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) error

SaveSetKeysCtx 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

go
func SaveSetKeysRef(client *Client, md any, expiration time.Duration, keys ...string) error

SaveSetKeysRefCtx 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

go
func SaveSetKeysRefCtx(client *Client, ctx context.Context, md any, expiration time.Duration, keys ...string) error

SaveSetKeysRefCtx 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

go
func SaveSets[T IDer](client *Client, keyFns []func(string) string, expiration time.Duration, mds ...*T) error

SaveSets stores multiple IDer objects in Redis with multiple key functions

func SaveSetsCtx

go
func SaveSetsCtx[T IDer](client *Client, ctx context.Context, keyFns []func(string) string, expiration time.Duration, mds ...*T) error

SaveSetsCtx stores multiple IDer objects in Redis with multiple key functions using custom context

func WithAccessInterceptor

go
func WithAccessInterceptor(enable bool) lib_3rd.Option[config]

func WithAccessInterceptorReq

go
func WithAccessInterceptorReq(enable bool) lib_3rd.Option[config]

func WithAccessInterceptorRes

go
func WithAccessInterceptorRes(enable bool) lib_3rd.Option[config]

func WithAddrs

go
func WithAddrs(addrs ...string) lib_3rd.Option[config]

WithAddrs set addresses with host:port format

func WithConfig

go
func WithConfig(conf *config) lib_3rd.Option[config]

func WithDBNum

go
func WithDBNum(num int) lib_3rd.Option[config]

func WithDebugMode

go
func WithDebugMode(enable bool) lib_3rd.Option[config]

func WithEnvironment

go
func WithEnvironment(env string) lib_3rd.Option[config]

func WithLogger

go
func WithLogger(logger ...flog.FlogInf) lib_3rd.Option[config]

func WithMasterName

go
func WithMasterName(name string) lib_3rd.Option[config]

func WithMaxActiveConns

go
func WithMaxActiveConns(max int) lib_3rd.Option[config]

func WithMaxIdleConns

go
func WithMaxIdleConns(max int) lib_3rd.Option[config]

func WithMaxRetries

go
func WithMaxRetries(max int) lib_3rd.Option[config]

func WithMetricInterceptor

go
func WithMetricInterceptor(enable bool) lib_3rd.Option[config]

func WithMinIdleConns

go
func WithMinIdleConns(min int) lib_3rd.Option[config]

func WithName

go
func WithName(name string) lib_3rd.Option[config]

func WithOnFail

go
func WithOnFail(onFail string) lib_3rd.Option[config]

func WithPassword

go
func WithPassword(password string) lib_3rd.Option[config]

WithPassword set password

func WithPoolSize

go
func WithPoolSize(size int) lib_3rd.Option[config]

func WithPoolTimeout

go
func WithPoolTimeout(timeout time.Duration) lib_3rd.Option[config]

func WithReadOnlyMode

go
func WithReadOnlyMode(enable bool) lib_3rd.Option[config]

func WithReadTimeout

go
func WithReadTimeout(timeout time.Duration) lib_3rd.Option[config]

func WithSlowLogThreshold

go
func WithSlowLogThreshold(threshold time.Duration) lib_3rd.Option[config]

func WithStatServerName

go
func WithStatServerName(name string) lib_3rd.Option[config]

func WithTraceInterceptor

go
func WithTraceInterceptor(enable bool) lib_3rd.Option[config]

func WithWriteTimeout

go
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.

go
type Client struct {
    // contains filtered or unexported fields
}

func (*Client) Client

go
func (c *Client) Client() rueidis.Client

func (*Client) ClientBloomFilter

go
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

go
func (c *Client) ClientCompact() rueidiscompat.Cmdable

Using like go-redis

func (*Client) ClientCountingBloomFilter

go
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

go
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

go
func (c *Client) Close() error

Close đóng kết nối redis.

func (*Client) Connection

go
func (c *Client) Connection() rueidis.Client

Connection trả về client rueidis được sử dụng bên trong.

func (*Client) Liveness

go
func (c *Client) Liveness() bool

Liveness trả về true khi dịch vụ Redis được xem là “sống”

func (*Client) LockClient

go
func (c *Client) LockClient() *lockClient

LockClient trả về distributed lock client.

func (*Client) Logger

go
func (c *Client) Logger() flog.FlogInf

Logger trả về logger của client.

func (*Client) Readiness

go
func (c *Client) Readiness() bool

Readiness trả về true khi dịch vụ Redis sẵn sàng phục vụ

type Err

go
type Err string

func (Err) Error

go
func (e Err) Error() string

type IDer

go
type IDer interface {
    GetID() string
}

type Lock

Lock represents an obtained, distributed Lock.

go
type Lock struct {
    // contains filtered or unexported fields
}

func (*Lock) Key

go
func (l *Lock) Key() string

Key returns the redis key used by the Lock.

func (*Lock) Metadata

go
func (l *Lock) Metadata() string

Metadata returns the metadata of the Lock.

func (*Lock) Refresh

go
func (l *Lock) Refresh(ctx context.Context, ttl time.Duration, opts ...LockOption) error

Refresh extends the Lock with a new TTL. May return ErrNotObtained if refresh is unsuccessful.

func (*Lock) Release

go
func (l *Lock) Release(ctx context.Context) error

Release manually releases the Lock. May return ErrLockNotHeld.

func (*Lock) TTL

go
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

go
func (l *Lock) Token() string

Token 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.

go
type LockOption func(c *lockOption)

func WithLockOptionMetadata

go
func WithLockOptionMetadata(md string) LockOption

WithLockOptionMetadata thêm metadata vào Lock.

func WithLockOptionRetryStrategy

go
func WithLockOptionRetryStrategy(retryStrategy RetryStrategy) LockOption

WithLockOptionRetryStrategy 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.

go
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.

go
type RetryStrategy interface {
    // NextBackOff returns the next backOff duration.
    NextBackOff() time.Duration
}

func LockOptionExponentialBackOffRetry

go
func LockOptionExponentialBackOffRetry(min, max time.Duration) RetryStrategy

LockOptionExponentialBackOffRetry 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

go
func LockOptionLimitRetry(s RetryStrategy, max int) RetryStrategy

LockOptionLimitRetry limits the number of retries to max attempts.

func LockOptionLinearBackOffRetry

go
func LockOptionLinearBackOffRetry(backOff time.Duration) RetryStrategy

LockOptionLinearBackOffRetry allows retries regularly with customized intervals

func LockOptionNoRetry

go
func LockOptionNoRetry() RetryStrategy

--------------------------------No Retry----------------------------------- LockOptionNoRetry acquire the Lock only once.

Generated by gomarkdoc