Orleans Initial Contact (1) Introduction Example

 [Return navigation]

After a brief understanding of Orleans, we can use several examples to deepen our impression.

I. An Introduction to Orleans

This example follows Orleans Initial Examples. https://www.cnblogs.com/gaopang/articles/7379802.html)

1. Create

First create a solution for four projects, as shown in the figure

  

The four projects are:

  1. Client: Obviously, that's what runs GrainClient. It communicates with Host, which requires it to refer to the IGrains project. This is a console project.
  2. Host: It's also obvious that Silo runs inside. It should refer to the Grains project and the IGrains project because it hosts the Grain (which requires a reference to the Grains class) and requires communication between Grain instances (which requires a reference to the IGrains project), which is a console project.
  3. Grains: This implements all the interfaces specified by IGrain and implements all Grain classes, including their methods and fields. (It requires a reference to IGrain.... Nonsense) This is a class library project.
  4. IGrains: Place all the interfaces that the Grains class extends here. This is a class library project.

Then use NuGet to refer to Microsoft.Orleans.Server

  

Next, use NuGet to refer to Microsoft.Orleans.Client

  

2. Coding

  IGrains.IBasic

  public interface IBasic : IGrainWithIntegerKey
    {
        Task<string> SayHello(string hellostr);
    }

  Grains.BasicGrain

  public class BasicGrain : Grain, IGrains.IBasic
    {
        public Task<string> SayHello(string hellostr)
        {
            Console.WriteLine("{0} : {1}", DateTime.Now.ToString("HH: mm:ss.fff"), hellostr);
            return Task.FromResult<string>("done");
        }
    }

  Host.Program

  class Program
    {
        static void Main(string[] args)
        {
            //Get a configuration example
            //He needs two ports. The first port 2334 is for silo and silo The second 1234 is for interception. client Requested
            var config = Orleans.Runtime.Configuration.ClusterConfiguration.LocalhostPrimarySilo(2234, 1234);
            //Initialize a silohost,Here we use Orleans Provided silohost Instead of silo,among silo Named Ba;
            SiloHost siloHost = new SiloHost("Ba", config);
            //Initialization warehouse
            siloHost.InitializeOrleansSilo();
            //start-up
            siloHost.StartOrleansSilo();

            //Check it out.
            if (siloHost.IsStarted)
            {
                Console.WriteLine("silohost Startup success");
            }
            else
            {
                Console.WriteLine("Startup failure");
            }
            Console.ReadKey();
        }
    }

  

    class Program
    {
        static void Main(string[] args)
        {
            //Waiting for the server to start up
            Console.ReadKey();
            //Then I smartly hit the return button.
            Run();
            Console.ReadKey();
        }

        static async void Run()
        {
            //Getting a configuration class with built-in methods,This class specifies that the server port is 1234
            //Configuration files can be used, but I'll use this simple configuration class first.
            var config = Orleans.Runtime.Configuration.ClientConfiguration.LocalhostSilo(1234);

            //Initialize a GrainClient
            GrainClient.Initialize(config);

            //from silo Where, get a BasicGrain Interface
            IGrains.IBasic agrain = GrainClient.GrainFactory.GetGrain<IGrains.IBasic>(314);

            //Call the method inside and wait for it to return
            string result = await agrain.SayHello("Not so bad");
            Console.WriteLine(result);
        }
    }

3. Operation

But there was a problem when running Client.

  

I don't know how to solve it yet, so I'm stuck here.

Follow-up solutions:

After a careful examination, I found that my original host project did not quote the Grains project and the IGrains project. After the reference, the whole project can run completely.

 

2. Quick Start Example

This example follows the Quick Start Example in Microsoft Orleans Introduction Guide (https://www.cnblogs.com/endv/p/6147976.html)

1. Create

Similarly, create a solution for four projects, which is named Orleans Samples.

  

The structure of the project is similar to that of the previous example, which also refers to Microsoft.Orleans.Server and Microsoft.Orleans.Client.

The difference is that this example uses a different interface from the previous one.

2. Coding

  IUserService

    public interface IUserService : IGrainWithIntegerKey
    {
        Task<bool> Exist(string mobileNumber);
    }

  UserService

    public class UserService : Grain, IUserService
    {
        public Task<bool> Exist(string mobileNumber)
        {
            return Task.FromResult<bool>(mobileNumber == "15665699774");
        }
    }

  Server

    class Program
    {
        static void Main(string[] args)
        {
            using (var host = new SiloHost("Default"))
            {
                host.InitializeOrleansSilo();
                host.StartOrleansSilo();
                Console.WriteLine("Start successfully!");
                Console.ReadLine();
                host.StopOrleansSilo();
            }
        }
    }

  Client

    class Program
    {
        static void Main(string[] args)
        {
            System.Threading.Thread.Sleep(15000);
            GrainClient.Initialize();

            while (true)
            {
                Console.WriteLine("Please enter the user's mobile phone number:");
                var mobileNumber = Console.ReadLine();
                //Because of what we have adopted here. grain Inherited IGrainWithIntegerKey ,So we use the call numeric type key=10 To create this grain,
                //Some might ask key What is it? He's the only one who identifies it. grain Yes, when you specify one key At that time, Orleans It creates one, which first goes to
                //Look in your storage medium(If you are configured, memory storage is used by default, which is suitable for the development period, and the production environment needs to be in a state, so you need to configure it to a place where persistent storage can be stored, such as sqlserver etc.)
                //If you find it, go back directly. If you don't find it, go back according to the one you specified. key Then create one, and here it is. grain Activation, specific and detailed, can see the official question about Grain Chapter 1.
                var userService = GrainClient.GrainFactory.GetGrain<IUserService>(10);
                //C#A new expression grammar, which is much more convenient and saves us stitching strings.
                Console.WriteLine($"user{mobileNumber},{(userService.Exist(mobileNumber).Result ? "Already exist" : "Non-existent")}");
            }

        }
    }

3. Operation

There's still something to do to get this Orleans running.

Add Orleans Configuration. XML to the Server directory

<?xml version="1.0" encoding="utf-8" ?>
<OrleansConfiguration xmlns="urn:orleans">
  <Globals>
    <StorageProviders>
      <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
      <Provider Type="Orleans.Storage.MemoryStorage" Name="Default" />
      <!--<Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore"/>-->
    </StorageProviders>
    <SeedNode Address="localhost" Port="22222"/>
    <Messaging ResponseTimeout="30s"/>
  </Globals>
  <Defaults>
    <Networking Address="localhost" Port="22222"/>
    <ProxyingGateway Address="localhost" Port="40000" />
    <Tracing DefaultTraceLevel="Info" TraceToConsole="true" TraceToFile="{0}-{1}.log" PropagateActivityId="false" BulkMessageLimit="1000">
      <TraceLevelOverride LogPrefix="Application" TraceLevel="Info" />
      <!--
<TraceLevelOverride LogPrefix="Runtime.Dispatcher" TraceLevel="Verbose" />
<TraceLevelOverride LogPrefix="AssemblyLoader.Silo" TraceLevel="Warning" />
-->
    </Tracing>
    <Statistics MetricsTableWriteInterval="30s" PerfCounterWriteInterval="30s" LogWriteInterval="300s" WriteLogStatisticsToTable="true" StatisticsCollectionLevel="Info"/>
  </Defaults>
</OrleansConfiguration>

Add ClientConfiguration.xml to the Client directory

<?xml version="1.0" encoding="utf-8" ?>
<ClientConfiguration xmlns="urn:orleans">
  <Gateway Address="localhost" Port="40000"/>
  <!-- To turn tracing off, set DefaultTraceLevel="Off" and have no overrides.
    For the trace log file name, {0} is replaced by "Client" and {1} is the current time. -->
  <Tracing DefaultTraceLevel="Info" TraceToConsole="false" TraceToFile="{0}-{1}.log" BulkMessageLimit="1000">
    <TraceLevelOverride LogPrefix="Runtime" TraceLevel="Info" />
    <TraceLevelOverride LogPrefix="Application" TraceLevel="Info" />
    <TraceLevelOverride LogPrefix="AssemblyLoader" TraceLevel="Warning" />
  </Tracing>
  <Statistics MetricsTableWriteInterval="300s" PerfCounterWriteInterval="30s" LogWriteInterval="300s" WriteLogStatisticsToTable="true" StatisticsCollectionLevel="Info"/>
  <Messaging ResponseTimeout="30s" ClientSenderBuckets="8192" MaxResendCount="0"/>
</ClientConfiguration>

And set properties for these two xml files - Advanced - copy to the output directory - copy if newer

Server (server) and Client (client) can be run separately to achieve results.

  

So far, a simple single-service Orleans has been completed, from this example you can understand Orleans simply. But there's still no idea how to build a distributed cluster server, so let's continue to learn about the West Side.

Keywords: C# xml encoding Mobile

Added by PunkGo on Sun, 19 May 2019 13:59:18 +0300