xxxxxxxxxx
git clone https://github.com/temporalio/docker-compose.git
cd docker-compose
docker-compose up
创建项目目录:
mkdir hello-temporal
初始化项目:
cd hello-temporal/
go mod init hello-temporal
下载最新版本的 Go SDK:
xxxxxxxxxx
go get -u go.temporal.io/sdk@latest
# 用于生成唯一 ID
go get github.com/google/uuid@v1.3.0
目录结构:
xxxxxxxxxx
.
├── activity
│ └── say_hello.go
├── go.mod
├── go.sum
├── main.go
├── worker
│ └── main.go
└── workflow
└── handle_name.go
activity/say_hello.go:
xxxxxxxxxx
package activity
import (
"context"
"fmt"
)
func SayHello(ctx context.Context, name string) (string, error) {
msg := fmt.Sprintf("Hello, %s!", name)
return msg, nil
}
workflow/handle_name.go:
xxxxxxxxxx
package workflow
import (
"fmt"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
"hello-temporal/activity"
"time"
)
func HandleName(ctx workflow.Context, name string) (string, error) {
retryPolicy := &temporal.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2.0,
MaximumInterval: time.Minute,
MaximumAttempts: 500,
}
options := workflow.ActivityOptions{
StartToCloseTimeout: time.Minute,
RetryPolicy: retryPolicy,
}
ctx = workflow.WithActivityOptions(ctx, options)
f := workflow.ExecuteActivity(ctx, activity.SayHello, name)
res := new(string)
err := f.Get(ctx, res)
if err != nil {
fmt.Printf("failed to say hello to %s, because %s\n", name, err)
return "", err
}
return *res, nil
}
worker/main.go:
xxxxxxxxxx
package main
import (
"go.temporal.io/sdk/client"
"go.temporal.io/sdk/worker"
"hello-temporal/activity"
"hello-temporal/workflow"
"log"
)
func main() {
c, err := client.Dial(client.Options{
HostPort: "127.0.0.1:7233",
Namespace: "default",
})
if err != nil {
log.Fatalln("unable to create Temporal client", err)
}
defer c.Close()
w := worker.New(c, "test_task_queue_name", worker.Options{})
w.RegisterWorkflow(workflow.HandleName)
w.RegisterActivity(activity.SayHello)
err = w.Run(worker.InterruptCh())
if err != nil {
log.Fatalln("unable to start Worker", err)
}
}
main.go:
xxxxxxxxxx
package main
import (
"context"
"fmt"
"github.com/google/uuid"
"go.temporal.io/sdk/client"
"hello-temporal/workflow"
"log"
)
func main() {
c, err := client.Dial(client.Options{
HostPort: "127.0.0.1:7233",
Namespace: "default",
})
if err != nil {
log.Fatalln("unable to create Temporal client", err)
}
defer c.Close()
options := client.StartWorkflowOptions{
ID: fmt.Sprintf("workflow_id-%s", uuid.New().String()),
TaskQueue: "test_task_queue_name",
}
workflowRun, err := c.ExecuteWorkflow(
context.Background(),
options, workflow.HandleName,
"Tim")
if err != nil {
log.Printf("failed to ExecuteWorkflow err: %s\n", err.Error())
return
}
log.Printf("Workflow Id: %s\n", workflowRun.GetID())
log.Printf("Run Id: %s\n", workflowRun.GetRunID())
var res string
if err := workflowRun.Get(context.Background(), &res); err != nil {
log.Fatalln("failed to execute Workflow", err)
}
log.Printf("result: %s\n", res)
}
启动 Worker:
x
go run worker/main.go
在另外一个窗口,启动 Workflow:
xxxxxxxxxx
go run. main.go