forked from lysu/go-saga
-
Notifications
You must be signed in to change notification settings - Fork 1
/
saga_example_test.go
57 lines (46 loc) · 1.95 KB
/
saga_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package saga_test
import (
"time"
"golang.org/x/net/context"
"github.com/cikupin/go-saga"
_ "github.com/cikupin/go-saga/storage/kafka"
)
// This example show how to initialize an Saga execution coordinator(SEC) and add Sub-transaction to it, then start a transfer transaction.
// In transfer transaction we deduce `100` from foo at first, then deposit 100 into `bar`, deduce & deduce wil both success or rollbacked.
func Example_sagaTransaction() {
// 1. Define sub-transaction method, anonymous method is NOT required, Just define them as normal way.
DeduceAccount := func(ctx context.Context, account string, amount int) error {
// Do deduce amount from account, like: account.money - amount
return nil
}
CompensateDeduce := func(ctx context.Context, account string, amount int) error {
// Compensate deduce amount to account, like: account.money + amount
return nil
}
DepositAccount := func(ctx context.Context, account string, amount int) error {
// Do deposit amount to account, like: account.money + amount
return nil
}
CompensateDeposit := func(ctx context.Context, account string, amount int) error {
// Compensate deposit amount from account, like: account.money - amount
return nil
}
// 2. Init SEC as global SINGLETON(this demo not..), and add Sub-transaction definition into SEC.
saga.StorageConfig.Kafka.ZkAddrs = []string{"0.0.0.0:2181"}
saga.StorageConfig.Kafka.BrokerAddrs = []string{"0.0.0.0:9092"}
saga.StorageConfig.Kafka.Partitions = 1
saga.StorageConfig.Kafka.Replicas = 1
saga.StorageConfig.Kafka.ReturnDuration = 50 * time.Millisecond
saga.AddSubTxDef("deduce", DeduceAccount, CompensateDeduce).
AddSubTxDef("deposit", DepositAccount, CompensateDeposit)
// 3. Start a saga to transfer 100 from foo to bar.
from, to := "foo", "bar"
amount := 100
ctx := context.Background()
var sagaID uint64 = 2
saga.StartSaga(ctx, sagaID).
ExecSub("deduce", from, amount).
ExecSub("deposit", to, amount).
EndSaga()
// 4. done.
}