---
title: "分散型ワーカーを作る"
slug: "create-a-distributed-worker"
abstract: "特定のソースの識別子を連絡先のバッチから削除するための分散ワーカーの作成方法。"
---
# 分散型ワーカーを作る

以下の分散 [ワーカー](https://doc.sitecore.com/xp/ja/developers/100/sitecore-experience-platform/workers.html "Workers") のサンプルは、xConnectクライアントAPIを使って、特定のソースを持つ識別子をコンタクトのバッチから削除しています。ワーカーはカスタムワーカーオプション辞書(SampleDistributedWorkerOptionsDictionary)を受け入れ、以下を定義します。

-   除去される識別子の識別元は
-   作業員の完全資格名

## 分散型労働者オプション辞書の作成

DistributedWorkerOptionsDictionaryクラスを使ってカスタム分散ワーカーのタスクを登録できます。ただし、ワーカーの完全な資格名と各辞書エントリの正しい名前とフォーマットを知っている必要があります。誤りのリスクを減らすために、すべての分散ワーカー向けにカスタムワーカーオプション辞書を作成することをお勧めします。

カスタムワーカーオプション辞書を作成するには:

-   SampleDistributedWorkerOptionsDictionary というクラスを作成し、以下のようにDistributedWorkerOptionsDictionaryを継承します。

using System.Collections.Generic;
using Newtonsoft.Json;
using Sitecore.Processing.Engine.Abstractions;

namespace Sitecore.Documentation.Examples
{
 public class SampleDistributedWorkerOptionsDictionary : DistributedWorkerOptionsDictionary
 {

 public SampleDistributedWorkerOptionsDictionary(string identifierSource) : base("Sitecore.Documentation.Examples.SampleDistributedWorker, Sitecore.Documentation.Examples", CreateDictionary(identifierSource))
 {

 }

 JsonConstructor
 protected SampleDistributedWorkerOptionsDictionary(IDictionary<string, string> dictionary) : base(dictionary)
 {
 }

 public static SampleDistributedWorkerOptionsDictionary Parse(IReadOnlyDictionary<string, string> options)
 {
 return new SampleDistributedWorkerOptionsDictionary(options"IdentifierSource");
 }

 private static IDictionary<string, string> CreateDictionary(string identifierSource)
 {
 var dictionary = new Dictionary<string, string>
 {
 {
 "IdentifierSource", identifierSource
 }
 };

 return dictionary;
 }
 }
}

分散型ワーカーオプション辞書を作成する際:

-   IDictionary<string, string>パラメータを受け入れるコンストラクタを含める必要があります。コンストラクタにはJsonConstructor属性で装飾されなければなりません。このコンストラクタがない場合、処理エンジンはワーカーを実行しようとした際に次のエラーを出します:「System.FormatException: Could not deserialize JSON text.」
-   以下のようなヘルパーメソッドを作成することが推奨されます:
    -   IReadOnlyDictionary<string, string>をオプション辞書に変換する(CreateDictionary())
    -   オプション辞書をIReadOnlyDictionary<string, string>に変換する(Parse())

## 分散労働者階級の作成

分散ワーカーを作成するには:

-   SampleDistributedWorkerというクラスを作成し、示されたようにIDistributedWorkerを実装します。
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Sitecore.Processing.Engine.Abstractions;
    using Sitecore.XConnect;
    
    namespace Sitecore.Documentation.Examples
    {
     public class SampleDistributedWorker : IDistributedWorker<Contact>
     {
     private readonly ILogger \_logger;
     private readonly IServiceProvider \_serviceProvider;
     private readonly SampleDistributedWorkerOptionsDictionary \_options;
    
     public SampleDistributedWorker(ILogger logger, SampleDistributedWorkerOptionsDictionary options, IServiceProvider serviceProvider)
    
     {
     \_logger = logger;
     \_serviceProvider = serviceProvider;
     \_options = options;
     }
    
     public SampleDistributedWorker(ILogger logger, IReadOnlyDictionary<string, string> options, IServiceProvider serviceProvider) : this (logger, SampleDistributedWorkerOptionsDictionary.Parse(options), serviceProvider)
     {
     }
    
     public async Task ProcessBatchAsync(IReadOnlyList<Contact> batch, CancellationToken token)
     {
     \_logger.LogInformation($"Run Worker: {GetType().Name}");
    
     if (batch == null)
     {
     throw new Exception("Batch is null.");
     }
    
     var contactsToUpdate = batch.Where(c => c.Identifiers.Any(x => x.Source == \_options"IdentifierSource"));
    
     using (IServiceScope scope = \_serviceProvider.CreateScope())
     {
     using (var xdbContext = scope.ServiceProvider.GetRequiredService<IXdbContext>())
     {
     foreach (var contact in contactsToUpdate)
     {
     xdbContext.RemoveContactIdentifier(new ContactReference(contact.Id.Value), contact.Identifiers.FirstOrDefault(x => x.Source == \_options"IdentifierSource"));
     }
    
     await xdbContext.SubmitAsync(token);
     }
     }
    
     return;
     }
    
     public void Dispose()
     {
     }
     }
    }
    

分散ワーカーを作成する際:

-   IReadOnlyDictionary<string, string>パラメータを受け入れるコンストラクタが必要です。このコンストラクタを含めないと、処理エンジンは起動せず、次のエラーが表示されます:「System.InvalidOperationException: 型に適したコンストラクタが見つかりませんでした。」

## 設定中のレジスタワーカー

Cortex処理エンジンでワーカーを登録するには:

1.  C:\\<PathToxConnect>\\App\_data\\jobs\\continuous\\ProcessingEngine\\App\_Data\\Config\\Global\\Processing\\sc.Processing.Documentation.Examples.xmlというファイルを作成し、以下の構成を追加します:
    
    <Settings>
     <Sitecore>
     <Processing>
     <Services>
     <TaskServicesFactory>
     <Options>
     <SampleDistributedWorker>
     <Type>Sitecore.Documentation.Examples.SampleDistributedWorker, Sitecore.Documentation.Examples</Type>
     </SampleDistributedWorker>
     </Options>
     </TaskServicesFactory>
     </Services>
     </Processing>
     </Sitecore>
    </Settings>
    
2.  処理エンジンを再起動します。これは構成の変更を登録するために必要です。
    

## カスタム分散ワーカーを使います

カスタムワーカーをコアロール環境(Content Managementなど)で使用するには:

-   示されたようにSampleDistributedWorkerOptionsDictionaryクラスを使って分散タスクを登録します:
    
    using System;
    using Microsoft.Extensions.DependencyInjection;
    using Sitecore.DependencyInjection;
    using Sitecore.Diagnostics;
    using Sitecore.Processing.Engine.Abstractions;
    
    namespace Sitecore.Documentation.Examples
    {
     public class Example
     {
     public async void Examples()
     {
     var \_taskManager = ServiceLocator.ServiceProvider.GetRequiredService<ITaskManager>();
    
     Guid taskId = await \_taskManager.RegisterDistributedTaskAsync(
     new ContactDataSourceOptionsDictionary(new ContactExpandOptions(), 20, 20),
     new SampleDistributedWorkerOptionsDictionary("RemoveMe"), null, TimeSpan.FromDays(1))
     .ConfigureAwait(false);
     }
     }
    }