idempotency

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetTyped

func GetTyped[T any](m Manager, ctx context.Context, key string) (T, bool, error)

GetTyped is a type-safe generic wrapper around Manager.Get. It automatically unmarshals the cached JSON result into the target type T.

Usage:

val, found, err := idempotency.GetTyped[MyResponse](m, ctx, key)

func SetTyped

func SetTyped[T any](m Manager, ctx context.Context, key string, result T, ttl time.Duration) error

SetTyped is a type-safe generic wrapper around Manager.Set. It accepts a typed value instead of any, providing compile-time type safety at the call site.

Usage:

err := idempotency.SetTyped[MyResponse](m, ctx, key, resp, 10*time.Minute)

Types

type IdempotencyKey

type IdempotencyKey struct {
	Key       string          // 幂等键(SHA256 hash)
	Result    json.RawMessage // 缓存的响应结果
	ExpiresAt time.Time       // 过期时间
}

IdempotencyKey 幂等键结构 用于缓存相同请求的响应,避免重复处理

type Manager

type Manager interface {
	// GenerateKey 根据输入生成幂等键
	GenerateKey(inputs ...any) (string, error)

	// Get 获取缓存的结果
	Get(ctx context.Context, key string) (json.RawMessage, bool, error)

	// Set 设置缓存结果
	Set(ctx context.Context, key string, result any, ttl time.Duration) error

	// Delete 删除缓存
	Delete(ctx context.Context, key string) error

	// Exists 检查幂等键是否存在
	Exists(ctx context.Context, key string) (bool, error)
}

Manager 幂等性管理器接口 提供幂等键的生成、存储和查询能力

func NewMemoryManager

func NewMemoryManager(logger *zap.Logger) Manager

NewMemoryManager 创建基于内存的幂等性管理器(仅用于测试)

func NewMemoryManagerWithCleanup

func NewMemoryManagerWithCleanup(logger *zap.Logger, cleanupInterval time.Duration) Manager

NewMemoryManagerWithCleanup 创建带自定义清理间隔的内存管理器

func NewRedisManager

func NewRedisManager(redis *redis.Client, prefix string, logger *zap.Logger) Manager

NewRedisManager 创建基于 Redis 的幂等性管理器

Jump to

Keyboard shortcuts

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