Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest Service Fabric Reliable Collection (Dictionary) example

I'm trying to implement the simplest usage of an Azure's Service Fabric Reliable Collection --- a Hello World example, as it were --- of an I​Reliable​Dictionary.

In this link an example is given. Yet this example requires a StateManager object, which I'm unsure how to create or even what it is. It seems an Actor is needed, and I'm looking to avoid Actors for now.

Could anyone provide an example of this?

Many thanks in advance

like image 405
Hugo Nava Kopp Avatar asked Jun 21 '17 16:06

Hugo Nava Kopp


People also ask

What is reliable service in service fabric?

Reliable Services is one of the programming models available on Service Fabric. Another is the Reliable Actor programming model, which provides a Virtual Actor application framework on top of the Reliable Services model. For more information on Reliable Actors, see Introduction to Service Fabric Reliable Actors.

What is Service Fabric?

Service Fabric is Microsoft's container orchestrator for deploying and managing microservices across a cluster of machines, benefiting from the lessons learned running Microsoft services at massive scale.


1 Answers

Never mind, I found the answer.

The crucial point is that one can't create reliable collections in Stateless Services, we necessarily need to create a Stateful Service if we want to make use of the Reliable Collections.

Here I found an example of an implementation of a Reliable Dictionary. I paste the code next, which should go in the MyStatefulService.cs class:

protected override async Task RunAsync(CancellationToken cancellationToken)
{

var myDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>("myDictionary");

while (true)
{
    cancellationToken.ThrowIfCancellationRequested();

    using (var tx = this.StateManager.CreateTransaction())
    {
        var result = await myDictionary.TryGetValueAsync(tx, "Counter");

        ServiceEventSource.Current.ServiceMessage(this, "Current Counter Value: {0}",
            result.HasValue ? result.Value.ToString() : "Value does not exist.");

        await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value);

        // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
        // discarded, and nothing is saved to the secondary replicas.
        await tx.CommitAsync();
    }

    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
like image 165
Hugo Nava Kopp Avatar answered Sep 30 '22 01:09

Hugo Nava Kopp