package model import ( "context" "database/sql" "fmt" "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/sqlx" ) var _ DeductionsModel = (*customDeductionsModel)(nil) type ( // DeductionsModel is an interface to be customized, add more methods here, // and implement the added methods in customDeductionsModel. DeductionsModel interface { deductionsModel InsertDeductionsTrans(ctx context.Context, deductions *Deductions, session sqlx.Session) (sql.Result, error) } customDeductionsModel struct { *defaultDeductionsModel } ) // NewDeductionsModel returns a model for the database table. func NewDeductionsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) DeductionsModel { return &customDeductionsModel{ defaultDeductionsModel: newDeductionsModel(conn, c, opts...), } } func (m *customDeductionsModel) InsertDeductionsTrans(ctx context.Context, deductions *Deductions, session sqlx.Session) (sql.Result, error) { query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (?, ?, ?)", m.table, deductionsRowsExpectAutoSet) ret, err := session.ExecCtx(ctx, query, deductions.UserId, deductions.Amount, deductions.TransactionId) if err != nil { return nil, err } deductionsTransactionIdKey := fmt.Sprintf("%s%v", cacheDeductionsTransactionIdPrefix, deductions.TransactionId) // 2. 更新缓存,保证所有缓存操作成功 cacheKeys := []string{deductionsTransactionIdKey} cacheErrors := make([]error, len(cacheKeys)) cacheErrors[0] = m.DelCacheCtx(ctx, deductionsTransactionIdKey) // 3. 检查缓存操作是否全部成功 for _, cacheErr := range cacheErrors { if cacheErr != nil { return nil, cacheErr // 返回第一个缓存更新失败的错误 } } return ret, err }