Creating a Service Fabric application with a stateless actor service

As part of the introduction to this chapter, we looked at the difference between stateful and stateless microservices. The Service Fabric application templates available are then further divided into Reliable Services (stateful/stateless) and Reliable Actors (stateful/stateless). When to use which one is something that will depend on the specific business requirement of your application.

To put it simply though, if you wanted to create a service that should be exposed to many users of your application at any one time, a Reliable Service would probably be a good fit. Think of a service exposing the latest exchange rates that can be consumed by many users or applications at once.

Again, looking back to the introduction of this chapter, we used the example of an online web store with a shopping cart. A Reliable Actor could be a good fit for every customer buying items, so you could have a shopping cart actor. The Reliable Actor as part of the Service Fabric framework is based on the Virtual Actor pattern. Have a look at the article on the Virtual Actor pattern at http://research.microsoft.com/en-us/projects/orleans/.

To show you how easy it is to create a microservice using a stateless actor service as an example, we will use Visual Studio to publish a service to the Service Fabric cluster and call that service from a console (client) application.

Getting ready

To complete this recipe, you must ensure that you have installed your local Service Fabric cluster on your local machine.

How to do it…

  1. In Visual Studio, create a new project by going to File | New | Project:
    How to do it…
  2. From the Visual C# node, expand the nodes until you see the Cloud node. When you click on it, you will see that Visual Studio now lists a new Service Fabric Application template. Select the Service Fabric Application template, call it sfApp, and click on OK:
    How to do it…
  3. Next, select Stateless Reliable Actor from the Create a Service window that pops up. We just called ours UtilitiesActor:
    How to do it…
  4. Once your solution is created, you will notice that it consists of three projects. These are:
    • sfApp
    • UtilitiesActor
    • UtilitiesActor.Interfaces
    How to do it…
  5. We will start off by modifying the IUtilitiesActor interface. This interface will simply require that UtilitiesActor implements a method called ValidateEmailAsync that takes an e-mail address as a parameter and returns a Boolean value indicating whether it is a valid email address or not:
    namespace UtilitiesActor.Interfaces
    {
        public interface IUtilitiesActor : IActor
        {
            Task<bool> ValidateEmailAsync(string emailToValidate);
        }
    }
  6. Next, open up your UtilitiesActor project and view the class. It will be underlined with a red squiggly line because it does not implement the interface member ValidateEmailAsync():
    How to do it…
  7. Using Ctrl + . (period), implement the interface. Remove all the other unnecessary default code (if any):
    How to do it…
  8. The implemented interface code inserted for you should look like this. At the moment, it only contains NotImplementedException. It is here that we will implement the code to validate the e-mail address:
    namespace UtilitiesActor
    {
        internal class UtilitiesActor : StatelessActor, IUtilitiesActor
        {
            public Task<bool> ValidateEmailAsync(string emailToValidate)
            {
                throw new NotImplementedException();
            }        
        }
    }
  9. We will use a regular expression to validate the e-mail address passed to this method via the parameter. Regular expressions are very powerful. I have, however, in all my years of programming, never written my own expression. These are readily available on the Internet, and you can create a utilities class (or extension methods class) for your own projects to reuse. You can make use of regular expressions and other code that is often used.

    Finally, you will notice the ActorEventSource code. This is simply just to create Event Tracing for Windows (ETW) events that will help you see what is happening in your application from the diagnostic events window in Visual Studio. To open the diagnostic events window, go to View, Other Windows and click on Diagnostic Events Viewer:

    internal class UtilitiesActor : StatelessActor, IUtilitiesActor
    {
        public async Task<bool> ValidateEmailAsync(string emailToValidate)
        {
            ActorEventSource.Current.ActorMessage(this, "Email Validation");
    
            return await Task.FromResult(Regex.IsMatch(emailToValidate, @"A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0- 9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9- ]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0- 9])?)", RegexOptions.IgnoreCase));
        }        
    }
  10. Be sure to add a reference to the System.Text.RegularExpressions namespace. Without it, you will not be able to use the regular expressions. If you added the regular expression in your code without adding the reference, Visual Studio will display a red squiggly line under the Regex method:
    How to do it…
  11. Using Ctrl + . (period), add the using statement to your project. This will bring the regular expression namespace into scope:
    How to do it…
  12. Now that we have created the interface and also added the implementation of that interface, it is time to add a client application that we will use for testing. Right-click on your solution and add a new project:
    How to do it…
  13. The easiest way is to add a simple console application. Call your client application sfApp.Client and click on the OK button:
    How to do it…
  14. After you have added your console application to your solution, your solution should look like this:
    How to do it…
  15. You will now need to add references to your client application. Right-click the References node in your sfApp.Client project and select Add Reference from the context menu:
    How to do it…
  16. Start off by adding a reference to the UtilitiesActor.Interfaces project:
    How to do it…
  17. You will also need to add references to several Service Fabric dynamic link libraries (DLLs). When you created your Service Fabric application, it should have added a folder called packages to your project folder structure. Browse to this folder and add your Service Fabric DLLs from there. After you have added the required DLLs, your project should look like this:
    How to do it…
  18. In the Program.cs file of your console application, you need to add the following code to the Main method:
    namespace sfApp.Client
    {
        class Program
        {
            static void Main(string[] args)
            {
                var actProxy = ActorProxy.Create<IUtilitiesActor> (ActorId.NewId(), "fabric:/sfApp");
    
                WriteLine("Utilities Actor {0} - Valid Email?: {1}", actProxy.GetActorId(), actProxy.ValidateEmailAsync ("[email protected]").Result);
                WriteLine("Utilities Actor {0} - Valid Email?: {1}", actProxy.GetActorId(), actProxy.ValidateEmailAsync ("invalid@[email protected]").Result);
                ReadLine();
            }
        }
    }

    All we are doing is creating a proxy for our actor and writing the output of the e-mail validation to the console window. Your client application is now ready.

  19. Before we can run the client application, however, we need to publish our service first. In Solution Explorer, right-click on the sfApp service and click on Publish from the context menu:
    How to do it…
  20. The Publish Service Fabric Application window will now be displayed. Click on the Select… button next to the Connection endpoint text box:
    How to do it…
  21. Select Local Cluster as your Connection endpoint and click on OK:
    How to do it…
  22. Change Target profile and Application Parameters File to Local.xml. When you are done, click on the Publish button:
    How to do it…
  23. If you navigate to http://localhost:19080/Explorer, you will notice that the service you created has been published to your local Service Fabric cluster:
    How to do it…
  24. You are now ready to run your client application. Right-click on the sfApp.Client project, and select Debug and Start new instance from the context menu:
    How to do it…
  25. The console application calls the validate method to check the e-mail addresses, and displays the results to the console window. The results are as expected:
    How to do it…
  26. We can, however, be more specific when creating the actor ID. We can give it a specific name. Modify your proxy code and create a new ActorId method, and give it any string value:
    var actProxy = ActorProxy.Create<IUtilitiesActor>(new ActorId("Utilities"), "fabric:/sfApp");
    
    WriteLine("Utilities Actor {0} - Valid Email?: {1}", actProxy.GetActorId(), actProxy.ValidateEmailAsync("[email protected]").Result) ;
    WriteLine("Utilities Actor {0} - Valid Email?: {1}", actProxy.GetActorId(), actProxy.ValidateEmailAsync("invalid@[email protected]").Resu lt);
    ReadLine();

    Note

    The ActorId method can take a parameter of type Guid, long or string.

  27. When you debug your client application again, you will notice that Utilities Actor now has a logical name (the same name you passed as a string value when creating a new ActorId method):
    How to do it…

How it works…

Creating your Service Fabric application and publishing it locally is a perfect solution for testing your application before publishing it to the cloud. Creating small independent microservices allows developers many benefits related to testing, debugging, and deploying efficient and robust code that your applications can leverage to ensure maximum availability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.30.210