demo.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.sxidc.com/yjp/dapr_client"
  6. "git.sxidc.com/yjp/dapr_client/saga"
  7. "time"
  8. )
  9. func main() {
  10. dapr_client.InitDAPR(10)
  11. defer dapr_client.DestroyDAPR()
  12. saga.Init("statestore", "test-saga")
  13. defer saga.Destroy()
  14. ok()
  15. rollback()
  16. for {
  17. }
  18. }
  19. func ok() {
  20. orchestrator := saga.GetInstance().BuildOrchestrator("test-ok", 5*time.Second).
  21. AddStep(&saga.Step{
  22. StepFunc: func() error {
  23. fmt.Println("one")
  24. return nil
  25. },
  26. StepRollbackFunc: func() error {
  27. fmt.Println("one rollback")
  28. return nil
  29. },
  30. }).
  31. AddStep(&saga.Step{
  32. StepFunc: func() error {
  33. fmt.Println("two")
  34. return nil
  35. },
  36. StepRollbackFunc: func() error {
  37. fmt.Println("two rollback")
  38. return nil
  39. },
  40. }).
  41. AddStep(&saga.Step{
  42. StepFunc: func() error {
  43. fmt.Println("three")
  44. return nil
  45. },
  46. StepRollbackFunc: nil,
  47. }).
  48. Output(func() (interface{}, error) {
  49. return "ok result", nil
  50. })
  51. result, err := orchestrator.Run()
  52. if err != nil {
  53. fmt.Println(err)
  54. return
  55. }
  56. fmt.Println("Result:", result)
  57. }
  58. func rollback() {
  59. orchestrator := saga.GetInstance().BuildOrchestrator("test-rollback", 5*time.Second).
  60. AddStep(&saga.Step{
  61. StepFunc: func() error {
  62. fmt.Println("one")
  63. return nil
  64. },
  65. StepRollbackFunc: func() error {
  66. fmt.Println("one rollback")
  67. return nil
  68. },
  69. }).
  70. AddStep(&saga.Step{
  71. StepFunc: func() error {
  72. fmt.Println("two")
  73. return nil
  74. },
  75. StepRollbackFunc: func() error {
  76. fmt.Println("two rollback")
  77. return nil
  78. },
  79. }).
  80. AddStep(&saga.Step{
  81. StepFunc: func() error {
  82. fmt.Println("three")
  83. return nil
  84. },
  85. StepRollbackFunc: nil,
  86. }).
  87. AddStep(&saga.Step{
  88. StepFunc: func() error {
  89. return errors.New("four error")
  90. },
  91. StepRollbackFunc: nil,
  92. }).
  93. Output(func() (interface{}, error) {
  94. return "should not come here", nil
  95. })
  96. result, err := orchestrator.Run()
  97. if err != nil {
  98. fmt.Println(err)
  99. return
  100. }
  101. fmt.Println("Result:", result)
  102. }