问题
When a cadence worker comes up it initializes certain resources like database connections and client for other services. What is the correct pattern to make these resources accessible from activity implementations?
回答1:
Go
You can pass anything your activity needs via the context to your activity.
Here is how it works:
1) Before you start your worker, set whatever you need as value to a context (below code happen at where you setup your worker):
myThriftClient := ... // create my thrift client
myContext := context.WithValue(context.Background(), "my_thrift_client", myThriftClient)
2) Use the context created in step1 as BackgroundActivityContext of the worker options that you use to start your worker:
workerOptions := cadence.WorkerOptions{
MetricsScope: myScope,
Logger: myLogger,
BackgroundActivityContext: myContext,
}
worker := cadence.NewWorker(service, domain, taskList, workerOptions)
3) In your activity code, retrieve your thrift client from the context:
func MyActivity(ctx context.Context) error {
myThriftClient := ctx.Value("my_thrift_client").(ThriftClient)
// now you can make thrift calls using myThriftClient
}
Java
Worker.registerActivityImplementations
accepts an activity object instance. So any dependencies can be associated with this object before it is registered with the worker.
Worker.Factory factory = new Worker.Factory(DOMAIN);
Worker worker = factory.newWorker(TASK_LIST);
// Initialize activities instance with all its dependencies
MyActivities activities = new MyActivitiesImpl(dbPool, serviceAClient);
worker.registerActivitiesImplementations(activities);
// Start listening to the workflow and activity task lists.
factory.start();
回答2:
In Java we use Suppliers to pass in stateful clients and services like gcs, database ... so on each activity run based on how we have implemeneted the get method of the Supplier, the requested client/service is provided to the activity without the need to instantiating them beforehand upon activityImpl instantiation.
来源:https://stackoverflow.com/questions/58170960/cadence-workflow-pass-host-specific-objects-like-database-connections-service