MicroService. Core simple MicroService framework I. Introduction,
MicroService. Core
MicroService.Core
The original intention is to easily create a microservice, which can be started as a Windows Service or Console mode. It uses OWin self-managed technology at the underlying layer, abandons the east-west set of Microsoft Mvc, and chooses Nancy, making the development process very comfortable and simple!
Quick Start 1. Create a console Project (requires. net 4.5 or above) 2. Install the Nuget package
PM> Install-Package MicroService.Core -Version 1.1.1
Or search in the Nuget Package ManagerMicroService.Core
Install.
3. compile Program. cs and enter the following code:
Add reference:using MicroService.Core;
Write the following code in the Main method:
1 var service = new MicroServiceBase("MyService");2 service.Run(args);
The content of the Program. cs file is as follows:
1 using MicroService.Core; 2 namespace MicroService.Samples 3 { 4 class Program 5 { 6 static void Main(string[] args) 7 { 8 var service = new MicroServiceBase("MyService"); 9 service.Run(args);10 }11 }12 }
Generate a project and open a command line window in the directory of the generated EXE file. Execute:
If the generated EXE file isMicroService.Samples.exe
1. Run in command line mode:
MicroService.Samples.exe --console
You can see the following running results:
2. Windows Service Mode
MicroService.Samples.exe --install
If the following occurs in the running result:
Because the windows service cannot be installed due to insufficient permissions, run the command line window with administrator permissions to execute the preceding command again, as shown below:
ViewWindows Services
List, you can see that the service is running properly:
4. How to test whether the service is running properly?
This microservice framework provides the service status address by default./health
, The default binding address ishttp://127.0.0.1:8080
, The following output is obtained from the browser access address http: // 127.0.0.1: 8080/health:
We can see some situations of the service, such as running times and exposed endpoints...
5. Are you surprised?
With only three lines of code and the using reference, only two lines of code can be used to provide external services that can run on the command line/windows service.API
Capability program.
Principle
- The integration of Owin gives her self-managed capabilities
- By implementing an internal ServiceBase class, she has the ability to run as a windows service.
- Integrating Nancy (http://nancyfx.org/) gives her the ability to easily open APIs
Some people may say that this is a bird? Don't worry. let's expand. What should we do? Let's start with a calculator. Input two numbers and return the sum of the two numbers.
Step 1: Write a Nancy module:
For the preparation of the Nancy module, please go to the link http://nancyfx.org/learning, as a technician, learning is essential skills. Of course, you can see that you don't have to worry about learning Nancy first. It's very easy to continue reading it!
1. Add a class
Create a new project namedAddModule
The code of the Nancy module is as follows:
1 using Nancy; 2 using System.Threading.Tasks; 3 namespace MicroService.Samples 4 { 5 public class AddModule : NancyModule 6 { 7 public AddModule() 8 { 9 Get["/add", true] = async (_, ctx) =>10 {11 return await Task.Run(() =>12 {13 int? num1 = Request.Query.num1;14 int? num2 = Request.Query.num2;15 if (num1.HasValue && num2.HasValue)16 {17 return $"{num1} + {num2} = {num1 + num2}";18 }19 return "Paramters num1 and num2 missing!";20 });21 };22 }23 }24 }
This code may be a little difficult for people without Nancy module experience, but the code is easy to understand!
Stop the running Windows Service, regenerate the project, and start the service.
Access the browser: http: // 127.0.0.1: 8080/add? Num1 = 1 & num2 = 2
If nothing happens, your running result should be the same as mine!
Maybe you have some idea here. Can't I use VS for debugging? The answer is yes!
Right-click the VS project, enter the project properties page, enter -- console in startup parameters under the debugging tab, and then start the project.
Now let's take a look at the running effect of the console:
Look at the Red Arrow and add two lines. The newly created module is loaded successfully!
Are exposed URLs listed?
At this point, I still don't feel like it shows his advantages. let's deal with this project!
2. Create a RedisService. cs class separately.
The Code is as follows:
1 using System; 2 namespace MicroService.Samples 3 { 4 public class RedisService 5 { 6 public string RedisServiceStatus 7 { 8 get 9 {10 var rnd = new Random().Next(1, 10);11 if (rnd % 3 == 0)12 {13 return "DOWN";14 }15 return "UP";16 }17 }18 }19 }
The code is very simple. It has only one read-only attribute and obtains the status (simulation) of the Redis service ). Next, we add him to the above/health
In the endpoint, the overall service status is displayed more intuitively.
Modify the code in the Program. cs class:
1 using MicroService. core; 2 using Nancy. tinyIoc; 3 namespace MicroService. samples 4 {5 class Program 6 {7 static void Main (string [] args) 8 {9 var service = new MicroServiceBase ("MyService"); 10 service. onServiceStarting + = Service_OnServiceStarting; 11 service. onServiceStatusUpdating + = Service_OnServiceStatusUpdating; 12 service. run (args); 13} 14 // <summary> 15 // Run the event 16 // </summary> 17 /// <Param name = "service"> </param> 18 // <param name = "container"> </param> 19 private static void Service_OnServiceStarting (20 MicroServiceBase service, 21 TinyIoCContainer container) 22 {23 var redisService = new RedisService (); 24 container. register (redisService ); 25} 26 // <summary> 27 // service status update event 28 // </summary> 29 // <param name = "service"> </param> 30 // <param name = "serviceStatus"> </param> 31 pri Vate static void Service_OnServiceStatusUpdating (32 MicroServiceBase service, 33 ServiceStatus serviceStatus) 34 {35 var redisService = service. GetComponent <RedisService> (); 36 if (redisService! = Null) 37 {38 serviceStatus. AddOrUpdate ("RedisStatus", redisService. RedisServiceStatus); 39} 40} 41} 42}
Someone may want to scold me. You can tease me. Is that simple with so many codes? In fact, it is not difficult to take a closer look!
Two events are added, and events and service status update events are executed before the service starts. In the event code executed before the service starts, A RedisService instance is registered using the TinyIoCContainer IoC Container built in Nancy. In the service status update eventservice.GetComponent<RedisService>()
Obtain the RedisService instance and add it in serviceStatus.
Run the command again to see the result:
In this way, we have completed a small microservice. Of course, this road is still long. This is just a core framework. If you are interested, you can study it in depth!
QQ: 491217650 mail: admin@mrhuo.com
It's time to go to bed at 03:52:10! Write Other tutorials later!
Github Open Source Address: https://github.com/mrhuo/MicroService.Core