NewLife.Net - Building Reliable Web Services

Network programs should be registered as system services to ensure their self-starting and stable and reliable operation!

In this session, let's talk about how to build a production-level network service.

Old rules, go to the source code first: https://github.com/nnhy/NewLife.Net.Tests

The system service function is supported by the brother framework of the network library and the Agent of the X component. It was also called XAgent in the past. You can find many articles by searching NewLife XAgent on the Internet.

XAgent is very young in X components, only 10 years old, designed in 2008, Lujiazui, Shanghai.

〇, the final effect 

Let's take a look at the final effect first, you can also telnet net.newlifex.com 1234 to see the effect

The window on the left is the network service program to be talked about this time, working in debug mode.

The right window is the last EchoTest client, connecting to the network service on the left.

1. Create a console project

Create a console project and reference NewLife.Core through nuget

Create a new service class MyService, which inherits from the generic base class AgentServiceBase<MyService>

Add a line of bootstrap to Program.Main:

class Program
{
    static void Main(String[] args)
    {
        // Boot into my service control class 
        MyService.ServiceMain();
    }
}

 Let's start to slowly improve our service class MyService

public MyService()
{
    ServiceName = "EchoAgent";
    DisplayName = " Echo Service " ;
    Description = " This is an example of an echo service from NewLife.Net! " ;

    // Prepare two worker threads, respectively responsible for outputting logs and sending time to the client 
    ThreadCount = 2 ;
    Intervals = new[] { 1, 5 };
}

Specify some basic parameters, you can guess the use by looking at the renderings

Service name, display name, description, that's all!

 

ThreadCount = 2 specifies two worker threads, and Intervals specifies that their polling periods are 1 second and 5 seconds respectively

 

The standard action for system services is to start and stop

MyNetServer _Server;
/// <summary>开始服务</summary>
/// <param name="reason"></param>
protected override void StartWork(String reason)
{
    // Instantiate the server, specify the port, and listen on Tcp/Udp/IPv4/IPv6 
    var svr = new MyNetServer
    {
        Port = 1234,
        Log = XTrace.Log
    };
    svr.Start();

    _Server = svr;

    base.StartWork(reason);
}

/// <summary>停止服务</summary>
/// <param name="reason"></param>
protected override void StopWork(String reason)
{
    _Server.TryDispose();
    _Server = null;

    base.StopWork(reason);
}

We overload the start function, initialize the network service, and restart the stop function to destroy the network service.

The MyNetServer here is copied from the previous routine.

The network service is a member resource to avoid being reclaimed by the GC.

 

XAgent brings multi-threaded task scheduling by default, and its core is Work (Int32 index)

///  <summary> The scheduler allows each task thread to execute Work regularly, and the index identifies the task </summary> 
///  <param name="index"></param> 
///  <returns></returns> 
public  override Boolean Work(Int32 index)
{
    switch (index)
    {
        case 0: ShowStat(_Server); break;
        case 1: SendTime(_Server); break;
    }
    return false;
}

private String _last;
 ///  <summary> Show server status </summary> 
///  <param name="ns"></param> 
private  void ShowStat(NetServer ns)
{
    var msg = ns.GetStat();
    if (msg == _last) return;

    _last = msg;

    WriteLog(msg);
}

///  <summary> Send time to all clients </summary> 
///  <param name="ns"></param> 
private  void SendTime(NetServer ns)
{
    var str = DateTime.Now.ToFullString() + Environment.NewLine;
    var buf = str.GetBytes();
    ns.SendAllAsync(buf);
}

XAgent is internally designed with a task scheduler, which will actually create two threads (specified by ThreadCount), each thread executes the Work (Int32 index) function regularly, and the index parameter is used to identify which task thread.

We only need a very simple switch, thread 0 is responsible for outputting the status of the server, once per second, thread 1 is responsible for sending the current server time to all sessions connected to the server.

 

A few more words about XAgent:

1. The task thread has a higher thread priority and has more opportunities to get CPU time than the general thread

2. The scheduler has a management thread with the highest priority, which is responsible for supervising all task threads. If the task thread crashes or times out, it will kill it and create a new one.

3. The management thread is also responsible for monitoring the number of threads, number of handles, memory usage, etc.

 

2. Development and debugging

 Since it is a console project, run it first and see:

The red font shows important information, the yellow font shows the menu, and the commonly used function is 235.

We choose 5, loop debugging, which is actually to simulate the service workflow in the console and let the network service run.

As you can see in the log below, it listens on 4 sockets.

 

2 is to install the service, that is, to install the current application as a Windows service. Special attention is paid here. Generally, administrator privileges are required to install successfully unless the system UAC is turned off.

3 is to start the service, which can only be seen after the service is installed.

 

Therefore, the XAgent program is not only a development and debugging console program, but also an operation console for installing and uninstalling, starting and stopping services, and a Windows service program itself!

Careful students can find that the installed Windows service is essentially EchoAgent.exe -s with the -s parameter.

 

3. Installation service

 Finally, we installed it on a public network server, tcp://net.newlifex.com:1234, and telnet to see the effect

As can be seen from the log file, its application type ApplicationType is Service, which is Windows Service.

The following log outputs the server status in the A0 thread (that is, task thread 0).

Online 1/1, current online/max online

Send 2/20/0, a total of 2 times, the maximum speed is 20 bytes per second, the current speed is 0 bytes per second

 

Since there is A0 thread, there will also be A1 and An (ThreadCount>n), which can be used to distinguish the logs output by different task threads.

 

So far, our Windows network service program has been developed and installed on the public network server to continue to provide Echo services to the outside world!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325952037&siteId=291194637