下载地址:http://lanzou.com.cn/id83063a9

项目列表:
Project Structure
Folder : jianshejisuanxitong
Files : 61
Size : 196.1 KB
Generated: 2026-03-20 18:16:23
jianshejisuanxitong/
├── README.md [191 B]
├── aspects/
│ ├── Adapter.sql [3.8 KB]
│ ├── Builder.py [6.4 KB]
│ ├── Controller.py [4.5 KB]
│ ├── Controller.ts [2.3 KB]
│ ├── Handler.js [4.5 KB]
│ ├── Manager.js [3.5 KB]
│ ├── Queue.js [4 KB]
│ └── Transformer.java [5.8 KB]
├── config/
│ ├── Cache.json [692 B]
│ ├── Converter.xml [1.7 KB]
│ ├── Handler.json [692 B]
│ ├── Observer.properties [612 B]
│ ├── Parser.properties [613 B]
│ ├── Registry.xml [1.7 KB]
│ └── application.properties [612 B]
├── dto/
│ ├── Dispatcher.cpp [1.4 KB]
│ ├── Dispatcher.py [5.6 KB]
│ ├── Factory.py [4.2 KB]
│ ├── Queue.go [3.5 KB]
│ ├── Service.ts [2.7 KB]
│ └── Util.cpp [1.4 KB]
├── lib/
│ ├── Resolver.jar [650 B]
│ └── Validator.jar [650 B]
├── mixins/
│ ├── Builder.java [7.3 KB]
│ ├── Executor.php [3 KB]
│ ├── Listener.java [7.1 KB]
│ ├── Processor.js [3.5 KB]
│ ├── Transformer.js [4 KB]
│ └── Validator.go [2.6 KB]
├── package.json [692 B]
├── pom.xml [1.4 KB]
├── session/
│ ├── Client.php [2.7 KB]
│ ├── Helper.cpp [1.6 KB]
│ ├── Observer.py [4.2 KB]
│ ├── Provider.go [3.4 KB]
│ ├── Resolver.ts [2.4 KB]
│ ├── Scheduler.cpp [1.5 KB]
│ ├── Scheduler.php [3.7 KB]
│ ├── Server.py [5.1 KB]
│ └── Worker.js [4.3 KB]
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ ├── Client.java [4.3 KB]
│ │ │ ├── Converter.java [4.6 KB]
│ │ │ ├── Engine.java [4.8 KB]
│ │ │ ├── Loader.java [4.4 KB]
│ │ │ ├── Repository.java [7 KB]
│ │ │ └── Server.java [6.7 KB]
│ │ └── resources/
│ └── test/
│ └── java/
├── stub/
│ ├── Loader.ts [2.4 KB]
│ ├── Manager.py [4.7 KB]
│ ├── Parser.php [3.2 KB]
│ ├── Pool.php [3.6 KB]
│ ├── Processor.sql [2.4 KB]
│ ├── Proxy.ts [2.8 KB]
│ ├── Registry.go [3 KB]
│ ├── Service.php [2.9 KB]
│ └── Wrapper.js [4.7 KB]
└── wrappers/
├── Buffer.go [3.1 KB]
├── Cache.sql [3 KB]
└── Util.cpp [1.6 KB]
go
package balance
import (
"errors"
"sync"
"time"
)
// Transaction 交易记录
type Transaction struct {
ID string
Amount float64
Type string // "income", "expense", "freeze"
Timestamp time.Time
Remark string
}
// Balance 余额结构
type Balance struct {
mu sync.RWMutex
Available float64 // 可用余额
Frozen float64 // 冻结余额
Total float64 // 总余额
History []Transaction
}
// NewBalance 创建新余额
func NewBalance(initialAmount float64) *Balance {
return &Balance{
Available: initialAmount,
Total: initialAmount,
History: make([]Transaction, 0),
}
}
// AddIncome 增加收入
func (b *Balance) AddIncome(amount float64, remark string) error {
b.mu.Lock()
defer b.mu.Unlock()
if amount <= 0 {
return errors.New("金额必须大于0")
}
b.Available += amount
b.Total += amount
b.History = append(b.History, Transaction{
ID: generateID(),
Amount: amount,
Type: "income",
Timestamp: time.Now(),
Remark: remark,
})
return nil
}
// DeductExpense 扣除支出
func (b *Balance) DeductExpense(amount float64, remark string) error {
b.mu.Lock()
defer b.mu.Unlock()
if amount <= 0 {
return errors.New("金额必须大于0")
}
if b.Available < amount {
return errors.New("可用余额不足")
}
b.Available -= amount
b.Total -= amount
b.History = append(b.History, Transaction{
ID: generateID(),
Amount: amount,
Type: "expense",
Timestamp: time.Now(),
Remark: remark,
})
return nil
}
func generateID() string {
return time.Now().Format("20060102150405") + randomString(6)
}
- 高级余额计算框架(支持并发和回滚)
go
package balance
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/google/uuid"
)
// Account 账户模型
type Account struct {
ID string json:"id"
UserID string json:"user_id"
Balance int64 json:"balance" // 使用分单位避免精度问题
Frozen int64 json:"frozen"
Version int64 json:"version" // 乐观锁版本号
CreatedAt time.Time json:"created_at"
UpdatedAt time.Time json:"updated_at"
}
// TransactionType 交易类型
type TransactionType string
const (
TypeIncome TransactionType = "income"
TypeExpense TransactionType = "expense"
TypeFreeze TransactionType = "freeze"
TypeUnfreeze TransactionType = "unfreeze"
)
// TransactionRecord 交易记录
type TransactionRecord struct {
ID string json:"id"
AccountID string json:"account_id"
Type TransactionType json:"type"
Amount int64 json:"amount"
BeforeBalance int64 json:"before_balance"
AfterBalance int64 json:"after_balance"
BeforeFrozen int64 json:"before_frozen"
AfterFrozen int64 json:"after_frozen"
Status string json:"status"
Remark string json:"remark"
CreatedAt time.Time json:"created_at"
}
// BalanceService 余额服务
type BalanceService struct {
db sql.DB
mu sync.RWMutex
cache map[string]Account
}
// TransferRequest 转账请求
type TransferRequest struct {
FromAccountID string json:"from_account_id"
ToAccountID string json:"to_account_id"
Amount int64 json:"amount"
Remark string json:"remark"
}
// 转账操作(事务保证一致性)
func (s BalanceService) Transfer(ctx context.Context, req TransferRequest) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// 扣减转出账户余额
if err := s.deductBalanceWithTx(ctx, tx, req.FromAccountID, req.Amount); err != nil {
return err
}
// 增加转入账户余额
if err := s.addBalanceWithTx(ctx, tx, req.ToAccountID, req.Amount); err != nil {
return err
}
// 记录交易流水
if err := s.recordTransactionWithTx(ctx, tx, req); err != nil {
return err
}
return tx.Commit()
}
// 带乐观锁的扣减操作
func (s BalanceService) deductBalanceWithTx(ctx context.Context, tx sql.Tx, accountID string, amount int64) error {
var account Account
var currentVersion int64
// 查询当前账户信息(带锁)
query := `SELECT id, balance, frozen, version FROM accounts WHERE id = $1 FOR UPDATE`
err := tx.QueryRowContext(ctx, query, accountID).Scan(
&account.ID, &account.Balance, &account.Frozen, ¤tVersion,
)
if err != nil {
return err
}
// 检查余额
if account.Balance < amount {
return fmt.Errorf("余额不足: 当前余额 %d, 需要 %d", account.Balance, amount)
}
// 更新余额,使用乐观锁
updateQuery := `UPDATE accounts SET balance = balance - $1, version = version + 1, updated_at = NOW()
WHERE id = $2 AND version = $3`
result, err := tx.ExecContext(ctx, updateQuery, amount, accountID, currentVersion)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return fmt.Errorf("更新失败,请重试")
}
return nil
}
- 高性能内存计算框架
go
package balance
import (
"context"
"sync"
"sync/atomic"
"time"
)
// AtomicBalance 原子操作余额
type AtomicBalance struct {
available int64 // 可用余额(分)
frozen int64 // 冻结余额(分)
mu sync.RWMutex
}
// NewAtomicBalance 创建原子余额
func NewAtomicBalance(initial int64) *AtomicBalance {
return &AtomicBalance{
available: initial,
}
}
// CASUpdate 比较并交换更新
func (b *AtomicBalance) CASUpdate(oldAvailable, newAvailable int64) bool {
return atomic.CompareAndSwapInt64(&b.available, oldAvailable, newAvailable)
}
// AddAmount 原子增加
func (b *AtomicBalance) AddAmount(delta int64) int64 {
return atomic.AddInt64(&b.available, delta)
}
// SubAmount 原子减少
func (b *AtomicBalance) SubAmount(delta int64) int64 {
for {
old := atomic.LoadInt64(&b.available)
if old < delta {
return -1
}
if atomic.CompareAndSwapInt64(&b.available, old, old-delta) {
return old - delta
}
}
}
// BatchOperation 批量操作
type BatchOperation struct {
Operations []Operation
Results chan OperationResult
}
type Operation struct {
ID string
Type string
Amount int64
}
type OperationResult struct {
OperationID string
Success bool
NewBalance int64
Error string
}
// BatchProcessor 批量处理器
type BatchProcessor struct {
balances map[string]*AtomicBalance
mu sync.RWMutex
}
func (bp BatchProcessor) ProcessBatch(ctx context.Context, batch BatchOperation) {
var wg sync.WaitGroup
for _, op := range batch.Operations {
wg.Add(1)
go func(operation Operation) {
defer wg.Done()
select {
case <-ctx.Done():
batch.Results <- OperationResult{
OperationID: operation.ID,
Success: false,
Error: "context cancelled",
}
return
default:
result := bp.processOperation(operation)
batch.Results <- result
}
}(op)
}
wg.Wait()
close(batch.Results)
}
- 使用示例
go
package main
import (
"fmt"
"log"
)
func main() {
// 简单余额计算器示例
balance := NewBalance(1000.00)
// 增加收入
err := balance.AddIncome(500.00, "工资")
if err != nil {
log.Printf("增加收入失败: %v", err)
}
// 扣除支出
err = balance.DeductExpense(200.00, "购物")
if err != nil {
log.Printf("扣除支出失败: %v", err)
}
fmt.Printf("可用余额: %.2f\n", balance.Available)
fmt.Printf("总余额: %.2f\n", balance.Total)
// 原子操作示例
atomicBal := NewAtomicBalance(10000) // 100.00元
// 原子增加
newBal := atomicBal.AddAmount(5000) // 增加50.00元
fmt.Printf("原子增加后余额: %d分\n", newBal)
// 原子减少
newBal = atomicBal.SubAmount(3000) // 减少30.00元
fmt.Printf("原子减少后余额: %d分\n", newBal)
// 批量操作示例
processor := &BatchProcessor{
balances: make(map[string]*AtomicBalance),
}
// 初始化账户
processor.balances["account1"] = NewAtomicBalance(100000)
processor.balances["account2"] = NewAtomicBalance(50000)
batch := &BatchOperation{
Operations: []Operation{
{ID: "op1", Type: "transfer", Amount: 10000},
{ID: "op2", Type: "transfer", Amount: 20000},
},
Results: make(chan OperationResult, 2),
}
go processor.ProcessBatch(context.Background(), batch)
for result := range batch.Results {
fmt.Printf("操作结果: %+v\n", result)
}
}
关键特性
并发安全: 使用互斥锁和原子操作
事务支持: 支持数据库事务和乐观锁
精度处理: 使用整数(分)避免浮点数精度问题
批量处理: 支持高并发批量操作
回滚机制: 支持操作回滚和补偿