Bagikan melalui


Host dengan Service Fabric

Orleans dapat dihosting di Azure Service Fabric menggunakan Microsoft.ServiceFabric.Services dan Microsoft.Orleans. Paket NuGet Server . Silo harus dihosting sebagai layanan tanpa partisi dan tanpa status karena Orleans mengelola distribusi biji-bijian itu sendiri. Opsi hosting lainnya, seperti dipartisi dan stateful, lebih kompleks dan tidak menghasilkan manfaat tanpa penyesuaian tambahan di pihak pengembang. Disarankan untuk menghosting Orleans tanpa partisi dan tanpa status.

Layanan stateless Service Fabric sebagai Silo

Baik Anda membuat Aplikasi Service Fabric baru atau menambahkan Orleans ke yang sudah ada, Anda memerlukan Microsoft.ServiceFabric.Services referensi paket dan Microsoft.Orleans.Server dalam proyek Anda. Proyek layanan stateless membutuhkan implementasi pada ICommunicationListener dan subkelas dari StatelessService.

Siklus hidup Silo mengikuti siklus hidup pendengar komunikasi yang khas:

Karena Orleans Silo mampu hidup dalam batas- batas , implementasinya ICommunicationListener adalah pembungkus IHostdi IHostsekitar . IHost diinisialisasi dalam OpenAsync metode dan dihentikan dengan anggun dalam CloseAsync metode :

ICommunicationListener IHost Interaksi
OpenAsync IHost Instans dibuat dan panggilan ke StartAsync dilakukan.
CloseAsync Panggilan ke StopAsync pada instans host ditunggu.
Abort Panggilan ke StopAsync dievaluasi secara paksa, dengan GetAwaiter().GetResult().

Dukungan kluster

Dukungan pengklusteran resmi tersedia dari berbagai paket termasuk:

Ada juga beberapa paket pihak ketiga yang tersedia untuk layanan lain seperti CosmosDB, Kubernetes, Redis, dan Aerospike. Untuk informasi selengkapnya, lihat Manajemen kluster di Orleans.

Contoh proyek

Dalam proyek layanan stateless, terapkan antarmuka seperti yang ICommunicationListener ditunjukkan dalam contoh berikut:

using Microsoft.Extensions.Hosting;
using Microsoft.ServiceFabric.Services.Communication.Runtime;

namespace ServiceFabric.HostingExample;

internal sealed class HostedServiceCommunicationListener : ICommunicationListener
{
    private IHost? _host;
    private readonly Func<Task<IHost>> _createHost;

    public HostedServiceCommunicationListener(Func<Task<IHost>> createHost) =>
        _createHost = createHost ?? throw new ArgumentNullException(nameof(createHost));

    /// <inheritdoc />
    public async Task<string?> OpenAsync(CancellationToken cancellationToken)
    {
        try
        {
            _host = await _createHost.Invoke();
            await _host.StartAsync(cancellationToken);
        }
        catch
        {
            Abort();
            throw;
        }

        // This service does not expose any endpoints to Service Fabric for discovery by others.
        return null;
    }

    /// <inheritdoc />
    public async Task CloseAsync(CancellationToken cancellationToken)
    {
        if (_host is { } host)
        {
            await host.StopAsync(cancellationToken);
        }

        _host = null;
    }

    /// <inheritdoc />
    public void Abort()
    {
        IHost? host = _host;
        if (host is null)
        {
            return;
        }

        using CancellationTokenSource cancellation = new();
        cancellation.Cancel(false);

        try
        {
            host.StopAsync(cancellation.Token).GetAwaiter().GetResult();
        }
        catch
        {
            // Ignore.
        }
        finally
        {
            _host = null;
        }
    }
}

Kelas HostedServiceCommunicationListener menerima Func<Task<IHost>> createHost parameter konstruktor. Ini kemudian digunakan untuk membuat IHost instans dalam OpenAsync metode .

Bagian berikutnya dari proyek layanan stateless adalah mengimplementasikan StatelessService kelas . Contoh berikut menunjukkan subkelas StatelessService kelas:

using System.Fabric;
using Microsoft.Extensions.Hosting;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;

namespace ServiceFabric.HostingExample;

public sealed class OrleansHostedStatelessService : StatelessService
{
    private readonly Func<StatelessServiceContext, Task<IHost>> _createHost;

    public OrleansHostedStatelessService(
        Func<StatelessServiceContext, Task<IHost>> createHost, StatelessServiceContext serviceContext)
        : base(serviceContext) =>
        _createHost = createHost ?? throw new ArgumentNullException(nameof(createHost));  

    /// <inheritdoc/>
    protected sealed override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        // Create a listener which creates and runs an IHost
        yield return new ServiceInstanceListener(
            context => new HostedServiceCommunicationListener(() => _createHost(context)),
            nameof(HostedServiceCommunicationListener));
    }
}

Dalam contoh sebelumnya, OrleansHostedStatelessService kelas bertanggung jawab untuk menghasilkan ICommunicationListener instans. Metode CreateServiceInstanceListeners ini dipanggil oleh runtime Service Fabric ketika layanan diinisialisasi.

Menarik kedua kelas ini bersama-sama, contoh berikut menunjukkan proyek layanan stateless lengkap Program.cs file:

using System.Fabric;
using Microsoft.Extensions.Hosting;
using Microsoft.ServiceFabric.Services.Runtime;
using ServiceFabric.HostingExample;

try
{
    // The ServiceManifest.XML file defines one or more service type names.
    // Registering a service maps a service type name to a .NET type.
    // When Service Fabric creates an instance of this service type,
    // an instance of the class is created in this host process.
    await ServiceRuntime.RegisterServiceAsync(
        "Orleans.ServiceFabric.Stateless",
        context => new OrleansHostedStatelessService(
            CreateHostAsync, context));

    ServiceEventSource.Current.ServiceTypeRegistered(
        Environment.ProcessId,
        typeof(OrleansHostedStatelessService).Name);

    // Prevents this host process from terminating so services keep running.
    await Task.Delay(Timeout.Infinite);
}
catch (Exception ex)
{
    ServiceEventSource.Current.ServiceHostInitializationFailed(
        ex.ToString());
    throw;
}

static async Task<IHost> CreateHostAsync(StatelessServiceContext context)
{
    await Task.CompletedTask;

    return Host.CreateDefaultBuilder()
        .UseOrleans((_, builder) =>
        {
            // TODO, Use real storage, something like table storage
            // or SQL Server for clustering.
            builder.UseLocalhostClustering();

            // Service Fabric manages port allocations, so update the 
            // configuration using those ports. Gather configuration from 
            // Service Fabric.
            var activation = context.CodePackageActivationContext;
            var endpoints = activation.GetEndpoints();

            // These endpoint names correspond to TCP endpoints 
            // specified in ServiceManifest.xml
            var siloEndpoint = endpoints["OrleansSiloEndpoint"];
            var gatewayEndpoint = endpoints["OrleansProxyEndpoint"];
            var hostname = context.NodeContext.IPAddressOrFQDN;
            builder.ConfigureEndpoints(hostname,
                siloEndpoint.Port, gatewayEndpoint.Port);
        })
        .Build();
}

Dalam kode sebelumnya:

  • Metode ini ServiceRuntime.RegisterServiceAsync mendaftarkan OrleansHostedStatelessService kelas dengan runtime Service Fabric.
  • CreateHostAsync Delegasi digunakan untuk membuat IHost instans.