遅延ワーカーの作成

Version:
日本語翻訳に関する免責事項

このページの翻訳はAIによって自動的に行われました。可能な限り正確な翻訳を心掛けていますが、原文と異なる表現や解釈が含まれる場合があります。正確で公式な情報については、必ず英語の原文をご参照ください。

次のサンプルの 遅延ワーカー は、xConnectクライアントAPIを使用して既知の連絡先を作成します。ワーカーは、以下を定義するカスタムワーカーオプションディクショナリ(SampleDeferredWorkerOptionsDictionary)を受け入れます。

  • 識別子と、連絡先に使用する識別子ソース

  • ワーカーの完全修飾名

遅延ワーカー オプション ディクショナリの作成

DistributedWorkerOptionsDictionaryクラスを使用して、カスタム遅延ワーカーのタスクを登録できます。ただし、ワーカーの完全修飾名と、各ディクショナリエントリの正しい名前と形式を知っている必要があります。エラーのリスクを減らすために、すべての遅延ワーカーに対してカスタム ワーカー オプション ディクショナリを作成することをお勧めします。ワーカーオプションディクショナリを作成するには:

  • 次に示すように、DeferredWorkerOptionsDictionaryを継承するSampleDeferredWorkerOptionsDictionaryという名前のクラスを作成します。

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

namespace Sitecore.Documentation.Examples
{
    public class SampleDeferredWorkerOptionsDictionary : DeferredWorkerOptionsDictionary
    {
        public SampleDeferredWorkerOptionsDictionary(string identifier, string identifierSource) : base("Sitecore.Documentation.Examples.SampleDeferredWorker, Sitecore.Documentation.Examples", CreateDictionary(identifier, identifierSource))
        {
        }

        [JsonConstructor]
        protected SampleDeferredWorkerOptionsDictionary(IDictionary<string, string> dictionary) : base(dictionary)
        {
        }

        public static SampleDeferredWorkerOptionsDictionary Parse(IReadOnlyDictionary<string, string> options)
        {
            return new SampleDeferredWorkerOptionsDictionary(options["Identifier"], options["IdentifierSource"]);
        }

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

            return dictionary;
        }
    }
}

遅延ワーカー オプション ディクショナリを作成する場合:

  • IDictionary<string, string>パラメーターを受け入れるコンストラクタを含める必要があります。コンストラクタはJsonConstructor属性で修飾する必要があります。このコンストラクタがないと、処理エンジンはワーカーを実行しようとすると、"System.FormatException: JSONテキストを逆シリアル化できませんでした" というエラーをスローします。

遅延ワーカー クラスの作成

遅延ワーカーを作成するには:

  • 次に示すように、IDeferredWorkerを実装するSampleDeferredWorkerという名前のクラスを作成します。

    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.Framework.Conditions;
    using Sitecore.Processing.Engine.Abstractions;
    using Sitecore.XConnect;
    
    namespace Sitecore.Documentation.Examples
    {
        public class SampleDeferredWorker : IDeferredWorker
        {
            private readonly ILogger _logger;
            private readonly SampleDeferredWorkerOptionsDictionary _options;
            private readonly IServiceProvider _serviceProvider;
    
            public SampleDeferredWorker(ILogger logger, SampleDeferredWorkerOptionsDictionary options, IServiceProvider serviceProvider)
            {
                _logger = logger;
                _serviceProvider = serviceProvider;
                _options = options;
            }
    
            public SampleDeferredWorker(ILogger logger, IReadOnlyDictionary<string, string> options, IServiceProvider serviceProvider) : this(logger, SampleDeferredWorkerOptionsDictionary.Parse(options), serviceProvider)
            {
            }
    
            public async Task RunAsync(CancellationToken token)
            {
                _logger.LogInformation($"Run Worker: {GetType().Name}");
    
                using (IServiceScope scope = _serviceProvider.CreateScope())
                {
                    using (var xdbContext = scope.ServiceProvider.GetRequiredService<IXdbContext>())
                    {
                        var testContact = new Contact(
                            new ContactIdentifier(_options["IdentifierSource"], _options["Identifier"], ContactIdentifierType.Known));
    
                        xdbContext.AddContact(testContact);
    
                        await xdbContext.SubmitAsync(CancellationToken.None);
    
                        // We need to execute search operation to make sure that contacts are indexed
                        List<Contact> contacts = await xdbContext.Contacts.Where(c => c.Identifiers.Any(i => i.Source == _options["Identifier"])).ToList(token);
                        Condition.Ensures(contacts, nameof(contacts)).IsNotEmpty();
                    }
                }
            }
    
            public void Dispose()
            {
            }
        }
    }

遅延ワーカーを作成する場合:

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

構成にワーカーを登録する

ワーカーをCortex Processing Engineに登録するには、次のようにします。

  1. C:\<PathToxConnect>\App_data\jobs\continuous\ProcessingEngine\App_Data\Config\Global\Processing\sc.Processing.Documentation.Examples.xmlという名前のファイルを作成し、次の設定を追加します。

    <Settings>
        <Sitecore>
            <Processing>
            <Services>
            <TaskServicesFactory>
                <Options>
                    <SampleDeferredWorker>
                    <Type>Sitecore.Documentation.Examples.SampleDeferredWorker, Sitecore.Documentation.Examples</Type>
                    </SampleDeferredWorker>
                </Options>
                </TaskServicesFactory>
            </Services>
            </Processing>
        </Sitecore>
    </Settings>
  2. Cortex Processing Engineを再起動します。これは、構成の変更を登録するために必要です。

カスタム遅延ワーカーの使用

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

  • 次に示すように、SampleDeferredWorkerOptionsDictionaryクラスを使用して遅延タスクを登録します。

    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 AsyncExamples()
            {
                var _taskManager = ServiceLocator.ServiceProvider.GetRequiredService<ITaskManager>();
    
                Guid taskId = await _taskManager.RegisterDeferredTaskAsync(
                        new SampleDeferredWorkerOptionsDictionary("MyrtleMcSitecore", "SampleIdentifierSource"),
                        null,
                        TimeSpan.FromHours(1))
                    .ConfigureAwait(false);
            }
        }
    }
この記事を改善するための提案がある場合は、 お知らせください!