service

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDB

func GetDB() *gorm.DB

GetDB 获取全局数据库实例

func GetRedis

func GetRedis() *redis.Client

GetRedis 获取全局 Redis 实例(不变)

func ScanKeys

func ScanKeys(ctx context.Context, client *redis.Client, pattern string, batchSize int64) ([]string, error)

ScanKeys 使用 SCAN 命令安全遍历匹配的 key 生产环境必须使用此函数而非 KEYS 命令,避免阻塞 Redis 主线程

Types

type CreateOptions

type CreateOptions struct {
	IfNotExists  bool // 如果表已存在则跳过
	DropIfExists bool // 如果表存在则删除后重建
}

CreateOptions 创建表的配置选项

type DBManager

type DBManager struct {
	DB *gorm.DB
}

DBManager 数据库管理器

func InitDB

func InitDB() (*DBManager, error)

InitDB 初始化数据库连接

func (*DBManager) Close

func (dm *DBManager) Close() error

Close 关闭数据库连接

type HavingCondition

type HavingCondition struct {
	Field    string      // 聚合字段/表达式名称(如 "COUNT(*)"、"SUM(amount)")
	Operator string      // 运算符: "=", ">", ">=", "<", "<=", "!="
	Value    interface{} // 比较值
}

HavingCondition 结构化的 HAVING 条件(支持运算符,类型安全)

type Index

type Index struct {
	Name    string   // 索引名称
	Columns []string // 索引字段
	Unique  bool     // 是否唯一索引
}

Index 索引定义

type LookupQueryOptions

type LookupQueryOptions struct {
	KeyPattern   string        // 键模式(用于批量查询)
	CacheExpire  time.Duration // 缓存过期时间
	FallbackToDB bool          // 缓存未命中时是否回源数据库
}

LookupQueryOptions 缓存查询配置选项

type LookupSingleOptions

type LookupSingleOptions struct {
	CacheExpire  time.Duration
	FallbackToDB bool
	Refresh      bool
}

LookupSingleOptions 单个缓存查询配置选项

type QueryOptions

type QueryOptions struct {
	Page             int                    // 页码(从1开始)
	PageSize         int                    // 每页数量
	OrderBy          string                 // 排序字段
	Order            string                 // 排序方向(ASC/DESC)
	Preload          []string               // 预加载关联
	Select           []string               // 指定查询字段
	Distinct         bool                   // 是否去重
	Group            string                 // 分组字段
	Having           map[string]interface{} // Having 条件(简易写法:仅支持 = 运算符)
	HavingConditions []HavingCondition      // Having 条件(结构化写法:支持全部运算符,推荐)
}

QueryOptions 查询配置选项

type QueryResult

type QueryResult[T any] struct {
	Data       []T   // 数据列表
	Total      int64 // 总数
	Page       int   // 当前页
	PageSize   int   // 每页数量
	TotalPages int   // 总页数
}

QueryResult 查询结果

type RedisManager

type RedisManager struct {
	Client *redis.Client
}

RedisManager Redis 管理器

func InitRedis

func InitRedis() (*RedisManager, error)

InitRedis 初始化 Redis 连接(不变)

func (*RedisManager) Close

func (rm *RedisManager) Close() error

Close 关闭 Redis 连接(不变)

func (*RedisManager) Delete

func (rm *RedisManager) Delete(ctx context.Context, keys ...string) error

Delete 删除缓存(不变)

func (*RedisManager) Exists

func (rm *RedisManager) Exists(ctx context.Context, key string) (bool, error)

Exists 检查键是否存在(不变)

func (*RedisManager) Get

func (rm *RedisManager) Get(ctx context.Context, key string, dest interface{}) error

Get 获取缓存(不变)

func (*RedisManager) GetMultiple

func (rm *RedisManager) GetMultiple(ctx context.Context, keys []string) (map[string][]byte, error)

GetMultiple 批量获取缓存(不变)

func (*RedisManager) Set

func (rm *RedisManager) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error

Set 设置缓存(带过期时间)—— 修改在这里

func (*RedisManager) SetMultiple

func (rm *RedisManager) SetMultiple(ctx context.Context, items map[string]interface{}, expiration time.Duration) error

SetMultiple 批量设置缓存 —— 修改在这里

type ServiceManager

type ServiceManager[T any] struct {
	Resource     T      // 被管理的资源
	ResourceName string // 资源名称
	TableName    string // 表名
	Schema       string // 数据库模式
	CacheKeyType string // 缓存键
	CacheKeyName string // 缓存键名称
	// contains filtered or unexported fields
}

func NewServiceManager

func NewServiceManager[T any](resource T) *ServiceManager[T]

NewServiceManager 创建一个新的 ServiceManager 实例 通过reflect获取名字自动赋值给ResourceName和TableName还有keyname

func (*ServiceManager[T]) BatchDecrement

func (sm *ServiceManager[T]) BatchDecrement(
	ctx context.Context,
	column string,
	value interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) (int64, error)

BatchDecrement 批量减少字段值 (复用 Increment 逻辑)

func (*ServiceManager[T]) BatchDelete

func (sm *ServiceManager[T]) BatchDelete(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (int64, error)

BatchDelete 批量删除数据

func (*ServiceManager[T]) BatchIncrement

func (sm *ServiceManager[T]) BatchIncrement(
	ctx context.Context,
	column string,
	value interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) (int64, error)

BatchIncrement 批量增加字段值

func (*ServiceManager[T]) BatchInsert

func (sm *ServiceManager[T]) BatchInsert(ctx context.Context, data []T, batchSize int) error

func (*ServiceManager[T]) BatchSoftDelete

func (sm *ServiceManager[T]) BatchSoftDelete(ctx context.Context, queryFunc func(*gorm.DB) *gorm.DB) (int64, error)

func (*ServiceManager[T]) BatchUpdate

func (sm *ServiceManager[T]) BatchUpdate(
	ctx context.Context,
	updates map[string]interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) (int64, error)

BatchUpdate 批量更新数据

func (*ServiceManager[T]) BatchUpsert

func (sm *ServiceManager[T]) BatchUpsert(
	ctx context.Context,
	data []T,
	conflictColumns []string,
	updateColumns []string,
	batchSize int,
) error

BatchUpsert 批量 Upsert 操作

func (*ServiceManager[T]) CountQuery

func (sm *ServiceManager[T]) CountQuery(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (int64, error)

CountQuery 条件计数

func (*ServiceManager[T]) Create

func (sm *ServiceManager[T]) Create(ctx context.Context, opts *CreateOptions) error

Create 创建数据表

func (*ServiceManager[T]) CreateWithIndexes

func (sm *ServiceManager[T]) CreateWithIndexes(ctx context.Context, opts *CreateOptions, indexes []Index) error

CreateWithIndexes 创建数据表并添加索引

func (*ServiceManager[T]) Decrement

func (sm *ServiceManager[T]) Decrement(
	ctx context.Context,
	column string,
	value interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) error

Decrement 减少字段值

func (*ServiceManager[T]) DecrementByID

func (sm *ServiceManager[T]) DecrementByID(ctx context.Context, id interface{}, column string, value interface{}) error

func (*ServiceManager[T]) Delete

func (sm *ServiceManager[T]) Delete(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) error

Delete 删除单个数据

func (*ServiceManager[T]) DeleteByID

func (sm *ServiceManager[T]) DeleteByID(ctx context.Context, id interface{}) error

func (*ServiceManager[T]) DropTable

func (sm *ServiceManager[T]) DropTable(ctx context.Context) error

DropTable 删除数据表

func (*ServiceManager[T]) ExistsInCache

func (sm *ServiceManager[T]) ExistsInCache(ctx context.Context, key string) (bool, error)

ExistsInCache 检查缓存中是否存在

func (*ServiceManager[T]) ExistsQuery

func (sm *ServiceManager[T]) ExistsQuery(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (bool, error)

ExistsQuery 检查是否存在满足条件的记录

func (*ServiceManager[T]) ExtendCacheTTL

func (sm *ServiceManager[T]) ExtendCacheTTL(ctx context.Context, key string, expiration time.Duration) error

ExtendCacheTTL 延长缓存的过期时间

func (*ServiceManager[T]) GetCacheTTL

func (sm *ServiceManager[T]) GetCacheTTL(ctx context.Context, key string) (time.Duration, error)

GetCacheTTL 获取缓存的剩余过期时间

func (*ServiceManager[T]) GetFirst

func (sm *ServiceManager[T]) GetFirst(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (*T, error)

GetFirst 查询第一条记录(按创建时间)

func (*ServiceManager[T]) GetLast

func (sm *ServiceManager[T]) GetLast(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (*T, error)

GetLast 查询最后一条记录(按创建时间)

func (*ServiceManager[T]) GetQuery

func (sm *ServiceManager[T]) GetQuery(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
	opts *QueryOptions,
) (*QueryResult[T], error)

GetQuery 条件查询(支持分页) queryFunc: 用于构建查询条件的 lambda 函数 注意:纯只读 SELECT 不使用事务,直接复用 GetQueryWithoutTransaction

func (*ServiceManager[T]) GetQueryWithoutTransaction

func (sm *ServiceManager[T]) GetQueryWithoutTransaction(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
	opts *QueryOptions,
) (*QueryResult[T], error)

GetQueryWithoutTransaction 无事务的条件查询(用于高并发只读场景)

func (*ServiceManager[T]) GetRedisManager

func (sm *ServiceManager[T]) GetRedisManager() *RedisManager

func (*ServiceManager[T]) GetSingle

func (sm *ServiceManager[T]) GetSingle(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
	opts *SingleQueryOptions,
) (*T, error)

GetSingle 查询单个记录 queryFunc: 用于构建查询条件的 lambda 函数

func (*ServiceManager[T]) GetSingleByID

func (sm *ServiceManager[T]) GetSingleByID(
	ctx context.Context,
	id interface{},
	opts *SingleQueryOptions,
) (*T, error)

GetSingleByID 根据主键 ID 查询单个记录

func (*ServiceManager[T]) GetSingleOrCreate

func (sm *ServiceManager[T]) GetSingleOrCreate(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
	createData *T,
) (*T, bool, error)

GetSingleOrCreate 查询单个记录,不存在则创建

func (*ServiceManager[T]) GetSingleWithLock

func (sm *ServiceManager[T]) GetSingleWithLock(
	ctx context.Context,
	queryFunc func(*gorm.DB) *gorm.DB,
) (*T, *gorm.DB, error)

GetSingleWithLock 加锁查询单个记录(用于后续更新)

func (*ServiceManager[T]) HasTable

func (sm *ServiceManager[T]) HasTable(ctx context.Context) (bool, error)

HasTable 检查表是否存在

func (*ServiceManager[T]) Increment

func (sm *ServiceManager[T]) Increment(
	ctx context.Context,
	column string,
	value interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) error

Increment 增加字段值

func (*ServiceManager[T]) IncrementByID

func (sm *ServiceManager[T]) IncrementByID(ctx context.Context, id interface{}, column string, value interface{}) error

func (*ServiceManager[T]) Insert

func (sm *ServiceManager[T]) Insert(ctx context.Context, data *T) error

func (*ServiceManager[T]) InvalidateCache

func (sm *ServiceManager[T]) InvalidateCache(ctx context.Context, keys ...string) error

InvalidateCache 使缓存失效

func (*ServiceManager[T]) InvalidateCacheByPattern

func (sm *ServiceManager[T]) InvalidateCacheByPattern(ctx context.Context, pattern string) error

InvalidateCacheByPattern 根据模式使缓存失效

func (*ServiceManager[T]) InvalidateSingleCache

func (sm *ServiceManager[T]) InvalidateSingleCache(ctx context.Context, key string) error

InvalidateSingleCache 使单个缓存失效

func (*ServiceManager[T]) InvalidateSingleCacheByID

func (sm *ServiceManager[T]) InvalidateSingleCacheByID(ctx context.Context, id interface{}) error

InvalidateSingleCacheByID 根据 ID 使单个缓存失效

func (*ServiceManager[T]) LookupQuery

func (sm *ServiceManager[T]) LookupQuery(
	ctx context.Context,
	keys []string,
	opts *LookupQueryOptions,
) (map[string]*T, error)

LookupQuery 从缓存中查询系列数据 keys: 要查询的缓存键列表

func (*ServiceManager[T]) LookupQueryByPattern

func (sm *ServiceManager[T]) LookupQueryByPattern(
	ctx context.Context,
	pattern string,
	opts *LookupQueryOptions,
) (map[string]*T, error)

LookupQueryByPattern 根据键模式从缓存中查询数据 LookupQueryByPattern 改进版:使用 SCAN 代替 KEYS

func (*ServiceManager[T]) LookupQueryWithRefresh

func (sm *ServiceManager[T]) LookupQueryWithRefresh(
	ctx context.Context,
	keys []string,
	queryFunc func(*gorm.DB, []string) *gorm.DB,
	buildKeyFunc func(*T) string,
	expiration time.Duration,
) (map[string]*T, error)

LookupQueryWithRefresh 从缓存查询数据,如果缓存不存在则从数据库加载并刷新缓存

func (*ServiceManager[T]) LookupSingle

func (sm *ServiceManager[T]) LookupSingle(
	ctx context.Context,
	key string,
	opts *LookupSingleOptions,
) (*T, error)

LookupSingle 从缓存中查询单个数据

func (*ServiceManager[T]) LookupSingleByID

func (sm *ServiceManager[T]) LookupSingleByID(ctx context.Context, id interface{}, expiration time.Duration) (*T, error)

func (*ServiceManager[T]) LookupSingleWithFallback

func (sm *ServiceManager[T]) LookupSingleWithFallback(
	ctx context.Context,
	key string,
	queryFunc func(*gorm.DB) *gorm.DB,
	expiration time.Duration,
) (*T, error)

LookupSingleWithFallback 核心方法:带自动回填的查询

func (*ServiceManager[T]) RefreshCache

func (sm *ServiceManager[T]) RefreshCache(
	ctx context.Context,
	keys []string,
	queryFunc func(*gorm.DB, []string) *gorm.DB,
	buildKeyFunc func(*T) string,
	expiration time.Duration,
) error

RefreshCache 刷新缓存(从数据库重新加载)

func (*ServiceManager[T]) RefreshSingleCacheFromDB

func (sm *ServiceManager[T]) RefreshSingleCacheFromDB(ctx context.Context, key string, queryFunc func(*gorm.DB) *gorm.DB, expiration time.Duration) error

func (*ServiceManager[T]) Save

func (sm *ServiceManager[T]) Save(ctx context.Context, data *T) error

Save 保存单个数据(GORM 的 Save 方法,会保存所有字段)

func (*ServiceManager[T]) SetQuery

func (sm *ServiceManager[T]) SetQuery(
	ctx context.Context,
	data []T,
	opts *SetQueryOptions,
) error

SetQuery 批量设置数据(新增或修改)

func (*ServiceManager[T]) SetSingle

func (sm *ServiceManager[T]) SetSingle(
	ctx context.Context,
	data *T,
	opts *SetSingleOptions,
) error

SetSingle 设置单个数据(新增或修改)

func (*ServiceManager[T]) ShutdownAsyncWorkers

func (sm *ServiceManager[T]) ShutdownAsyncWorkers()

ShutdownAsyncWorkers 关闭异步 worker pool,等待所有在途任务完成

func (*ServiceManager[T]) SoftDelete

func (sm *ServiceManager[T]) SoftDelete(ctx context.Context, queryFunc func(*gorm.DB) *gorm.DB) error

func (*ServiceManager[T]) SoftDeleteByID

func (sm *ServiceManager[T]) SoftDeleteByID(ctx context.Context, id interface{}) error

func (*ServiceManager[T]) Update

func (sm *ServiceManager[T]) Update(
	ctx context.Context,
	updates map[string]interface{},
	queryFunc func(*gorm.DB) *gorm.DB,
) error

Update 更新单个数据

func (*ServiceManager[T]) UpdateByID

func (sm *ServiceManager[T]) UpdateByID(ctx context.Context, id interface{}, updates map[string]interface{}) error

func (*ServiceManager[T]) Upsert

func (sm *ServiceManager[T]) Upsert(
	ctx context.Context,
	data *T,
	conflictColumns []string,
	updateColumns []string,
) error

Upsert 单个 Upsert 操作(插入或更新)

func (*ServiceManager[T]) WarmupCache

func (sm *ServiceManager[T]) WarmupCache(ctx context.Context, queryFunc func(*gorm.DB) *gorm.DB, buildKeyFunc func(*T) string, expiration time.Duration) error

func (*ServiceManager[T]) WritedownAllToCache

func (sm *ServiceManager[T]) WritedownAllToCache(ctx context.Context, buildKeyFunc func(*T) string, opts *WritedownQueryOptions) error

func (*ServiceManager[T]) WritedownIncremental

func (sm *ServiceManager[T]) WritedownIncremental(
	ctx context.Context,
	data []T,
	buildKeyFunc func(*T) string,
	compareFunc func(*T, *T) bool,
	opts *WritedownQueryOptions,
) error

WritedownIncremental 修复了 Get 和 Set 的返回值错误

func (*ServiceManager[T]) WritedownQuery

func (sm *ServiceManager[T]) WritedownQuery(
	ctx context.Context,
	data []T,
	buildKeyFunc func(*T) string,
	opts *WritedownQueryOptions,
) error

WritedownQuery 批量将数据写入缓存 使用 Pipeline + Set(TTL) 替代旧的 MSet+逐个Expire,一次网络往返完成一批写入

func (*ServiceManager[T]) WritedownQueryByIDs

func (sm *ServiceManager[T]) WritedownQueryByIDs(ctx context.Context, ids []interface{}, buildKeyFunc func(*T) string, opts *WritedownQueryOptions) error

func (*ServiceManager[T]) WritedownQueryFromDB

func (sm *ServiceManager[T]) WritedownQueryFromDB(ctx context.Context, queryFunc func(*gorm.DB) *gorm.DB, buildKeyFunc func(*T) string, opts *WritedownQueryOptions) error

--- 辅助方法保持不变 ---

func (*ServiceManager[T]) WritedownSingle

func (sm *ServiceManager[T]) WritedownSingle(
	ctx context.Context,
	key string,
	data *T,
	opts *WritedownSingleOptions,
) error

WritedownSingle 将单个数据写入缓存

func (*ServiceManager[T]) WritedownSingleAsync

func (sm *ServiceManager[T]) WritedownSingleAsync(
	ctx context.Context,
	key string,
	data *T,
	expiration time.Duration,
)

WritedownSingleAsync 异步将单个数据写入缓存(使用 worker pool) 非阻塞:任务队列满时丢弃本次写入并打印 warning

func (*ServiceManager[T]) WritedownSingleByID

func (sm *ServiceManager[T]) WritedownSingleByID(ctx context.Context, id interface{}, opts *WritedownSingleOptions) error

func (*ServiceManager[T]) WritedownSingleWithLock

func (sm *ServiceManager[T]) WritedownSingleWithLock(
	ctx context.Context,
	key string,
	queryFunc func(*gorm.DB) *gorm.DB,
	expiration time.Duration,
	lockTimeout time.Duration,
) (*T, error)

func (*ServiceManager[T]) WritedownSingleWithVersion

func (sm *ServiceManager[T]) WritedownSingleWithVersion(
	ctx context.Context,
	key string,
	data *T,
	version int64,
	expiration time.Duration,
) error

func (*ServiceManager[T]) WritedownWithPipeline

func (sm *ServiceManager[T]) WritedownWithPipeline(
	ctx context.Context,
	data []T,
	buildKeyFunc func(*T) string,
	opts *WritedownQueryOptions,
) error

WritedownWithPipeline 修复了 Pipeline 的调用错误

type SetQueryOptions

type SetQueryOptions struct {
	BatchSize        int  // 批次大小
	OnConflictUpdate bool // 冲突时是否更新
	InvalidateCache  bool // 是否使缓存失效
}

SetQueryOptions 批量设置配置选项

type SetSingleOptions

type SetSingleOptions struct {
	OnConflictUpdate bool // 冲突时是否更新
	InvalidateCache  bool // 是否使缓存失效
	ReturnUpdated    bool // 是否返回更新后的数据
}

SetSingleOptions 单个设置配置选项

type SingleQueryOptions

type SingleQueryOptions struct {
	Preload   []string // 预加载关联
	Select    []string // 指定查询字段
	ForUpdate bool     // 是否加锁查询(用于后续更新)
}

SingleQueryOptions 单个查询配置选项

type WritedownQueryOptions

type WritedownQueryOptions struct {
	Expiration time.Duration
	BatchSize  int
	Overwrite  bool
}

WritedownQueryOptions 批量写入缓存配置选项

type WritedownSingleOptions

type WritedownSingleOptions struct {
	Expiration time.Duration
	Overwrite  bool
	NX         bool
	XX         bool
}

WritedownSingleOptions 单个写入缓存配置选项

Jump to

Keyboard shortcuts

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