Browse Source

完成dapr包封装

yjp19871013@126.com 2 years ago
parent
commit
06974f09ef
3 changed files with 128 additions and 0 deletions
  1. 13 0
      saga/demo/components/statestore.yaml
  2. 2 0
      saga/demo/dapr_run.sh
  3. 113 0
      saga/demo/demo.go

+ 13 - 0
saga/demo/components/statestore.yaml

@@ -0,0 +1,13 @@
+apiVersion: dapr.io/v1alpha1
+kind: Component
+metadata:
+  name: statestore
+  namespace: default
+spec:
+  type: state.redis
+  version: v1
+  metadata:
+    - name: redisHost
+      value: localhost:6379
+    - name: redisPassword
+      value: ""

+ 2 - 0
saga/demo/dapr_run.sh

@@ -0,0 +1,2 @@
+#!/bin/bash
+dapr run --app-id dapr-client-demo --dapr-http-port 8000 --dapr-grpc-port 8001 --components-path ./components

+ 113 - 0
saga/demo/demo.go

@@ -0,0 +1,113 @@
+package main
+
+import (
+	"errors"
+	"fmt"
+	"git.sxidc.com/yjp/dapr_client"
+	"git.sxidc.com/yjp/dapr_client/saga"
+	"time"
+)
+
+func main() {
+	dapr_client.InitDAPR(10)
+	defer dapr_client.DestroyDAPR()
+
+	saga.Init("statestore", "test-saga")
+	defer saga.Destroy()
+
+	ok()
+	rollback()
+
+	for {
+	}
+}
+
+func ok() {
+	orchestrator := saga.GetInstance().BuildOrchestrator("test-ok", 5*time.Second).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("one")
+				return nil
+			},
+			StepRollbackFunc: func() error {
+				fmt.Println("one rollback")
+				return nil
+			},
+		}).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("two")
+				return nil
+			},
+			StepRollbackFunc: func() error {
+				fmt.Println("two rollback")
+				return nil
+			},
+		}).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("three")
+				return nil
+			},
+			StepRollbackFunc: nil,
+		}).
+		Output(func() (interface{}, error) {
+			return "ok result", nil
+		})
+
+	result, err := orchestrator.Run()
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+
+	fmt.Println("Result:", result)
+}
+
+func rollback() {
+	orchestrator := saga.GetInstance().BuildOrchestrator("test-rollback", 5*time.Second).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("one")
+				return nil
+			},
+			StepRollbackFunc: func() error {
+				fmt.Println("one rollback")
+				return nil
+			},
+		}).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("two")
+				return nil
+			},
+			StepRollbackFunc: func() error {
+				fmt.Println("two rollback")
+				return nil
+			},
+		}).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				fmt.Println("three")
+				return nil
+			},
+			StepRollbackFunc: nil,
+		}).
+		AddStep(&saga.Step{
+			StepFunc: func() error {
+				return errors.New("four error")
+			},
+			StepRollbackFunc: nil,
+		}).
+		Output(func() (interface{}, error) {
+			return "should not come here", nil
+		})
+
+	result, err := orchestrator.Run()
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+
+	fmt.Println("Result:", result)
+}