0

ケイデンス ワーカーが起動すると、データベース接続や他のサービスのクライアントなどの特定のリソースが初期化されます。アクティビティの実装からこれらのリソースにアクセスできるようにするための正しいパターンは何ですか?

4

2 に答える 2

1

行け

コンテキストを介してアクティビティに必要なものをアクティビティに渡すことができます。

仕組みは次のとおりです。

1) ワーカーを開始する前に、必要なものを値としてコンテキストに設定します (以下のコードは、ワーカーをセットアップする場所で行われます)。

myThriftClient := ... // create my thrift client
myContext := context.WithValue(context.Background(), "my_thrift_client", myThriftClient)

2) ステップ 1 で作成したコンテキストを、ワーカーの開始に使用するワーカー オプションの BackgroundActivityContext として使用します。

workerOptions := cadence.WorkerOptions{
    MetricsScope:          myScope,
    Logger:                myLogger,
    BackgroundActivityContext: myContext,
}
worker := cadence.NewWorker(service, domain, taskList, workerOptions)

3) アクティビティ コードで、コンテキストからリサイクル クライアントを取得します。

func MyActivity(ctx context.Context) error { 
  myThriftClient := ctx.Value("my_thrift_client").(ThriftClient)
  // now you can make thrift calls using myThriftClient
}

ジャワ

Worker.registerActivityImplementationsアクティビティ オブジェクト インスタンスを受け入れます。そのため、ワーカーに登録する前に、依存関係をこのオブジェクトに関連付けることができます。

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();
于 2019-09-30T15:26:17.993 に答える