Temporal is a workflow orchestration system for building highly reliable systems.
Encore works great with Temporal, and this guide shows you how to integrate Temporal into your Encore application.
Next it's time to create a Temporal Workflow. We'll base this on the Temporal Hello World
example.
Create a new Encore service named greeting:
greeting/greeting.go
package greeting
import (
"context""fmt""go.temporal.io/sdk/client""go.temporal.io/sdk/worker""encore.dev"
)
// Use an environment-specific task queue so we can use the same// Temporal Cluster for all cloud environments.var (
envName = encore.Meta().Environment.Name
greetingTaskQueue = envName + "-greeting"
)
//encore:servicetype Service struct {
client client.Client
worker worker.Worker
}
funcinitService() (*Service, error) {
c, err := client.Dial(client.Options{})
if err != nil {
returnnil, fmt.Errorf("create temporal client: %v", err)
}
w := worker.New(c, greetingTaskQueue, worker.Options{})
err = w.Start()
if err != nil {
c.Close()
returnnil, fmt.Errorf("start temporal worker: %v", err)
}
return &Service{client: c, worker: w}, nil
}
func(s *Service) Shutdown(force context.Context) {
s.client.Close()
s.worker.Stop()
}
Next it's time to define some workflows. These need to be in the same service,
so add a new workflow package inside the greeting service, containing
a workflow and activity definition in separate files:
Then, go back to the greeting service and register the workflow and activity:
greeting/greeting.go
// Import the package at the top:import"encore.app/greeting/workflow"// Add these lines to `initService`, below the call to `worker.New`:
w.RegisterWorkflow(workflow.Greeting)
w.RegisterActivity(workflow.ComposeGreeting)
Now let's create an Encore API that triggers this workflow.
To run it in the cloud, you will need to use Temporal Cloud or your own, self-hosted Temporal cluster.
The easiest way to automatically pick up the correct cluster address is to use Encore's config functionality.
package greeting
TemporalServer: [
// These act as individual case statements
if #Meta.Environment.Cloud == "local" { "localhost:7233" },
// TODO: configure this to match your own cluster address
"my.cluster.address:7233",
][0] // Return the first value which matches the condition
Finally go back to greeting/greeting.go and update the client.Dial call to look like:
With that, Encore will automatically connect to the correct Temporal cluster, using a local cluster
for local development and your cloud-hosted cluster for everything else.