锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 开源技术 / ServiceMonitor.NetCore、.NetCore入门经典例子和.NetCore入门经典视频
服务方向
人工智能数据处理
人工智能培训
kaldi数据准备
小语种语音识别
语音识别标注
语音识别系统
语音识别转文字
kaldi开发技术服务
软件开发
运动控制卡上位机
机械加工软件
软件开发培训
Java 安卓移动开发
VC++
C#软件
汇编和破解
驱动开发
联系方式
固话:0371-63888850
手机:138-0381-0136
Q Q:396806883
微信:ryysoft

ServiceMonitor.NetCore、.NetCore入门经典例子和.NetCore入门经典视频


简介

这个例子从codeproject.com上找到,对.NET Core的特性表达的充分,复杂度适中,所以推荐给大家学习,锐英源对它也录制了视频,视频费用50元。

本文内容分2部分,视频PPT前段内容和翻译内容,翻译内容从寒冰屋博客下载,对博主致谢。

视频PPT内容

学习目标

部署
效果
.NET Core易用性
综合性:数据库,逻辑,通信输出
架构
通信接口
逻辑
理解后能独立写出,近中级程序员水平

 

部署

数据库
appsettings.json

部署数据库

EnvironmentCategory
包含环境的所有类别:开发,qa和生产
细节的数据化是产品化思维的体现
会处理相关的数据表明逻辑能力有明显提高

数据库逻辑

using (var dbContext = GetServiceMonitorDbContext())
{
dbContext.ServiceCategories.Add(new ServiceCategory { Name = "Database" });
dbContext.ServiceCategories.Add(new ServiceCategory { Name = "RESTful API" });
dbContext.ServiceCategories.Add(new ServiceCategory { Name = "Server" });
一个数据库上下文对象管理所有数据表,是层级思想的体现,主项目只关心用,其它层只关注实现
这里其它层放到其它项目里,更好管理

寒冰屋的翻译

介绍

本文介绍如何创建服务监视器应用程序,但它是什么?简单来说:它是一个允许监视网络中的服务并保存监视结果到数据库的应用程序,本例中为SQL Server。

我知道有很多工具可以提供这个功能,还有更好的工具,可以用钱买,但本文的意图是展示如何使用.NET核心能力来构建开发人员可以扩展以满足自定义要求的应用程序。

基本思想是这样的:有一个以无限方式运行的进程来监视主机,数据库和API; 将监控结果保存在SQL Server数据库中,然后我们可以为最终用户构建一个精美的UI并显示每个服务的状态,我们可以有很多目标进行监控,但最好是允许用户订阅特定服务而不是全部; 例如,DBA需要观察数据库服务器而不是API,开发人员需要观察开发数据库和API等。

还要考虑在开发室中安装大型显示器并观察服务状态,并且最好的情况是使用图表。:)

一个特殊功能可能是让一个通知服务在一个或多个服务失败的情况下为所有管理员发送消息,在这种情况下,服务意味着目标,如主机,数据库,API。

在本文中,我们将使用以下服务进行监控:

名称

描述

主机

Ping现有主机

数据库

打开并关闭现有数据库的连接

RESTful API

从现有API中获取一个操作

背景

正如我们之前所说,我们将创建一个应用程序来监视现有目标(主机,数据库,API),因此我们需要掌握有关这些概念的基本知识。

主机将使用ping操作进行监控,因此我们将添加与网络相关的包以执行此操作。

数据库将通过开放和关闭连接进行监视,不使用集成安全性,因为您需要使用凭据模拟服务监视器进程,因此在这种情况下,最好让特定用户与数据库连接,并且只有这样才能避免黑客攻击。

RESTful API将使用REST客户端进行监视,以定位返回简单JSON的操作。

数据库

在存储库内部,有一个名为\ Resources \ Database的目录,该目录包含相关的数据库文件,请确保按以下顺序运行以下文件:

文件名

描述

00 - Database.sql

数据库定义

01 - Tables.sql

表定义

02 - Constraints.sql

约束(主键,外键和唯一性)

03 - Rows.sql

初始数据

我们可以在这里找到数据库脚本。

                                                                                                       表说明

描述

EnvironmentCategory

包含环境的所有类别:开发,qa和生产

ServiceCategory

包含服务的所有类别:数据库,rest API,服务器,URL和Web服务

Service

包含所有服务定义

ServiceWatcher

包含C#端的所有组件以执行监视操作

ServiceEnvironment

包含服务和环境的关系,例如我们可以定义一个以不同环境命名的FinanceService服务:开发,qa和生产

ServiceEnvironmentStatus

包含每个环境的每个服务的状态

ServiceEnvironmentStatusLog

包含每个服务环境状态的详细信息

Owner

包含代表所有所有者的应用程序的用户列表

ServiceOwner

包含服务和所有者之间的关系

User

包含观看服务的所有用户

ServiceUser

包含服务和用户之间的关系

请不要忘记我们正在使用在本地计算机上运行的解决方案,资源目录中有一个示例API来执行测试,但您需要更改连接字符串并根据您的上下文添加服务。

另外我不建议在ServiceEnvironment表中公开真实的连接字符串,请向您的DBA请求单个用户只能对目标数据库执行打开连接,以防数据库的安全性成为您的任务,创建特定的用户来执行仅打开与数据库的连接并防止泄露敏感信息。

.NET核心解决方案

现在我们需要为此解决方案定义项目,以获得有关项目范围的清晰概念:

项目名

类型

描述

ServiceMonitor.Core

类库

包含与数据库存储相关的所有定义

ServiceMonitor.Common

类库

包含ServiceMonitor项目的常见定义,例如观察者,序列化器和客户端(REST)

ServiceMonitor.WebApi

Web API

包含Web API控制器,用于读取和写入有关监视的信息

ServiceMonitor

控制台应用

包含监控所有服务的过程

ServiceMonitor.Core

该项目包含实体和数据库访问的所有定义,因此我们需要为项目添加以下包:

名称

描述

Microsoft.EntityFrameworkCore.SqlServer

最新版本

通过EF Core提供对SQL Server的访问

该项目包含三个层次:业务逻辑,数据库访问和实体。

DashboardService 类代码:

using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ServiceMonitor.Core.BusinessLayer.Contracts;
using ServiceMonitor.Core.BusinessLayer.Responses;
using ServiceMonitor.Core.DataLayer;
using ServiceMonitor.Core.DataLayer.DataContracts;
using ServiceMonitor.Core.EntityLayer;

namespace ServiceMonitor.Core.BusinessLayer
{
public class DashboardService : Service, IDashboardService
{
public DashboardService(ILogger<DashboardService> logger, ServiceMonitorDbContext dbContext)
: base(logger, dbContext)
{
}

public async Task<IListResponse<ServiceWatcherItemDto>> GetActiveServiceWatcherItemsAsync()
{
Logger?.LogDebug("'{0}' has been invoked", nameof(GetActiveServiceWatcherItemsAsync));

var response = new ListResponse<ServiceWatcherItemDto>();

try
{
response.Model = await DbContext.GetActiveServiceWatcherItems().ToListAsync();

Logger.LogInformation("The service watch items were loaded successfully");
}
catch (Exception ex)
{
response.SetError(Logger, nameof(GetActiveServiceWatcherItemsAsync), ex);
}

return response;
}

public async Task<IListResponse<ServiceStatusDetailDto>> GetServiceStatusesAsync(string userName)
{
Logger.LogDebug("'{0}' has been invoked", nameof(GetServiceStatusesAsync));

var response = new ListResponse<ServiceStatusDetailDto>();

try
{
var user = await DbContext.GetUserAsync(userName);

if (user == null)
{
Logger.LogInformation("There isn't data for user '{0}'", userName);

return new ListResponse<ServiceStatusDetailDto>();
}
else
{
response.Model = await DbContext.GetServiceStatuses(user).ToListAsync();

Logger?.LogInformation("The service status details for '{0}' user were loaded successfully", userName);
}
}
catch (Exception ex)
{
response.SetError(Logger, nameof(GetServiceStatusesAsync), ex);
}

return response;
}

public async Task<ISingleResponse<ServiceEnvironmentStatus>> GetServiceStatusAsync(ServiceEnvironmentStatus entity)
{
Logger.LogDebug("'{0}' has been invoked", nameof(GetServiceStatusAsync));

var response = new SingleResponse<ServiceEnvironmentStatus>();

try
{
response.Model = await DbContext.GetServiceEnvironmentStatusAsync(entity);
}
catch (Exception ex)
{
response.SetError(Logger, nameof(GetServiceStatusAsync), ex);
}

return response;
}
}
}

ServiceMonitor.Common

约定

  • IWatcher
  • IWatchResponse
  • ISerializer

IWatcher 接口代码:

  • using System.Threading.Tasks;
  •  
  • namespace ServiceMonitor.Common.Contracts
  • {
  •     public interface IWatcher
  •     {
  •         string ActionName { get; }
  •  
  •         Task<WatchResponse> WatchAsync(WatcherParameter parameter);
  •     }
  • }

IWatchResponse 接口代码:

  • namespace ServiceMonitor.Common.Contracts
  • {
  •     public interface IWatchResponse
  •     {
  •         bool Success { get; set; }
  •  
  •         string Message { get; set; }
  •  
  •         string StackTrace { get; set; }
  •     }
  • }

ISerializer 接口代码:

  • namespace ServiceMonitor.Common.Contracts
  • {
  •     public interface ISerializer
  •     {
  •         string Serialize<T>(T obj);
  •  
  •         T Deserialze<T>(string source);
  •     }
  • }

观察者

这些是实现:

  • DatabaseWatcher
  • HttpRequestWatcher
  • PingWatcher

DatabaseWatcher 类代码:

  • using System;
  • using System.Data.SqlClient;
  • using System.Threading.Tasks;
  • using ServiceMonitor.Common.Contracts;
  •  
  • namespace ServiceMonitor.Common
  • {
  •     public class DatabaseWatcher : IWatcher
  •     {
  •         public string ActionName
  •             => "OpenDatabaseConnection";
  •  
  •         public async Task<WatchResponse> WatchAsync(WatcherParameter parameter)
  •         {
  •             var response = new WatchResponse();
  •  
  •             using (var connection = new SqlConnection(parameter.Values["ConnectionString"]))
  •             {
  •                 try
  •                 {
  •                     await connection.OpenAsync();
  •  
  •                     response.Success = true;
  •                 }
  •                 catch (Exception ex)
  •                 {
  •                     response.Success = false;
  •                     response.Message = ex.Message;
  •                     response.StackTrace = ex.ToString();
  •                 }
  •             }
  •  
  •             return response;
  •         }
  •     }
  • }
  • HttpWebRequestWatcher 类代码:

    1. using System;
    2. using System.Threading.Tasks;
    3. using ServiceMonitor.Common.Contracts;
    4.  
    5. namespace ServiceMonitor.Common
    6. {
    7.     public class HttpRequestWatcher : IWatcher
    8.     {
    9.         public string ActionName
    10.             => "HttpRequest";
    11.  
    12.         public async Task<WatchResponse> WatchAsync(WatcherParameter parameter)
    13.         {
    14.             var response = new WatchResponse();
    15.  
    16.             try
    17.             {
    18.                 var restClient = new RestClient();
    19.  
    20.                 await restClient.GetAsync(parameter.Values["Url"]);
    21.  
    22.                 response.Success = true;
    23.             }
    24.             catch (Exception ex)
    25.             {
    26.                 response.Success = false;
    27.                 response.Message = ex.Message;
    28.                 response.StackTrace = ex.ToString();
    29.             }
    30.  
    31.             return response;
    32.         }
    33.     }
    34. }

    PingWatcher 类代码:

    1. using System.Net.NetworkInformation;
    2. using System.Threading.Tasks;
    3. using ServiceMonitor.Common.Contracts;
    4.  
    5. namespace ServiceMonitor.Common
    6. {
    7.     public class PingWatcher : IWatcher
    8.     {
    9.         public string ActionName
    10.             => "Ping";
    11.  
    12.         public async Task<WatchResponse> WatchAsync(WatcherParameter parameter)
    13.         {
    14.             var ping = new Ping();
    15.  
    16.             var reply = await ping.SendPingAsync(parameter.Values["Address"]);
    17.  
    18.             return new WatchResponse
    19.             {
    20.                 Success = reply.Status == IPStatus.Success ? true : false
    21.             };
    22.         }
    23.     }
    24. }

    ServiceMonitor.WebApi

    这个项目代表服务监视器的RESTful API,所以我们将有两个控制器:DashboardController和AdministrationController。仪表板具有与最终用户结果相关的所有操作,管理包含与保存信息(创建,编辑和删除)相关的所有操作。

    仪表板

    DashboardController 类代码:

    1. using System.Threading.Tasks;
    2. using Microsoft.AspNetCore.Mvc;
    3. using Microsoft.Extensions.Logging;
    4. using ServiceMonitor.Core.BusinessLayer.Contracts;
    5. using ServiceMonitor.WebApi.Responses;
    6.  
    7. namespace ServiceMonitor.WebApi.Controllers
    8. {
    9. #pragma warning disable CS1591
    10.     [Route("api/v1/[controller]")]
    11.     [ApiController]
    12.     public class DashboardController : ControllerBase
    13.     {
    14.         protected ILogger Logger;
    15.         protected IDashboardService Service;
    16.  
    17.         public DashboardController(ILogger<DashboardController> logger, IDashboardService service)
    18.         {
    19.             Logger = logger;
    20.             Service = service;
    21.         }
    22. #pragma warning restore CS1591
    23.  
    24.         ///<summary>
    25.         /// Gets service watcher items (registered services to watch with service monitor)
    26.         ///</summary>
    27.         ///<returns>A sequence of services to watch</returns>
    28.         [HttpGet("ServiceWatcherItem")]
    29.         [ProducesResponseType(200)]
    30.         [ProducesResponseType(204)]
    31.         [ProducesResponseType(500)]
    32.         public async Task<IActionResult> GetServiceWatcherItemsAsync()
    33.         {
    34.             Logger?.LogDebug("'{0}' has been invoked", nameof(GetServiceWatcherItemsAsync));
    35.  
    36.             var response = await Service.GetActiveServiceWatcherItemsAsync();
    37.  
    38.             return response.ToHttpResponse();
    39.         }
    40.  
    41.         ///<summary>
    42.         /// Gets the details for service watch
    43.         ///</summary>
    44.         ///<param name="id">Service ID</param>
    45.         ///<returns></returns>
    46.         [HttpGet("ServiceStatusDetail/{id}")]
    47.         [ProducesResponseType(200)]
    48.         [ProducesResponseType(204)]
    49.         [ProducesResponseType(500)]
    50.         public async Task<IActionResult> GetServiceStatusDetailsAsync(string id)
    51.         {
    52.             Logger?.LogDebug("'{0}' has been invoked", nameof(GetServiceStatusDetailsAsync));
    53.  
    54.             var response = await Service.GetServiceStatusesAsync(id);
    55.  
    56.             return response.ToHttpResponse();
    57.         }
    58.     }
    59. }

    管理

    AdministrationController 类代码:

    1. using System.Threading.Tasks;
    2. using Microsoft.AspNetCore.Mvc;
    3. using Microsoft.Extensions.Logging;
    4. using ServiceMonitor.Core.BusinessLayer.Contracts;
    5. using ServiceMonitor.WebApi.Requests;
    6. using ServiceMonitor.WebApi.Responses;
    7.  
    8. namespace ServiceMonitor.WebApi.Controllers
    9. {
    10. #pragma warning disable CS1591
    11.     [Route("api/v1/[controller]")]
    12.     [ApiController]
    13.     public class AdministrationController : ControllerBase
    14.     {
    15.         protected ILogger Logger;
    16.         protected IAdministrationService Service;
    17.  
    18.         public AdministrationController(ILogger<AdministrationController> logger, IAdministrationService service)
    19.         {
    20.             Logger = logger;
    21.             Service = service;
    22.         }
    23. #pragma warning restore CS1591
    24.  
    25.         ///<summary>
    26.         /// Saves a result from service watch action
    27.         ///</summary>
    28.         ///<param name="request">Service status result</param>
    29.         ///<returns>Ok if save it was successfully, Not found if service not exists else server internal error</returns>
    30.         [HttpPost("ServiceEnvironmentStatusLog")]
    31.         [ProducesResponseType(200)]
    32.         [ProducesResponseType(404)]
    33.         [ProducesResponseType(500)]
    34.         public async Task<IActionResult> PostServiceStatusLogAsync([FromBody]ServiceEnvironmentStatusLogRequest request)
    35.         {
    36.             Logger?.LogDebug("'{0}' has been invoked", nameof(PostServiceStatusLogAsync));
    37.  
    38.             var response = await Service
    39.                 .CreateServiceEnvironmentStatusLogAsync(request.ToEntity(), request.ServiceEnvironmentID);
    40.  
    41.             return response.ToHttpResponse();
    42.         }
    43.     }
    44. }

    ServiceMonitor

    这个项目包含Service Monitor Client的所有对象,在这个项目中,我们添加了Newtonsoft.Json用于JSON序列化的包,在ServiceMonitor.Common中有一个名称为ISerializer的接口,因为我不想强制使用特定的序列化程序,你可以改变它在这个层。:)
    ServiceMonitorSerializer 类代码:

    1. using Newtonsoft.Json;
    2. using ServiceMonitor.Common.Contracts;
    3.  
    4. namespace ServiceMonitor
    5. {
    6.     public class ServiceMonitorSerializer : ISerializer
    7.     {
    8.         public string Serialize<T>(T obj)
    9.             => JsonConvert.SerializeObject(obj);
    10.  
    11.         public T Deserialze<T>(string source)
    12.             => JsonConvert.DeserializeObject<T>(source);
    13.     }
    14. }

    接下来,我们将开始MonitorController类,在这个类中,我们将执行所有观察操作,并通过Service Monitor API 中的AdministrationController将所有结果保存在数据库中。
    MonitorController 类代码:

    1. using System;
    2. using System.Threading;
    3. using System.Threading.Tasks;
    4. using Microsoft.Extensions.Logging;
    5. using ServiceMonitor.Common;
    6. using ServiceMonitor.Common.Contracts;
    7. using ServiceMonitor.Models;
    8.  
    9. namespace ServiceMonitor
    10. {
    11.     public class MonitorController
    12.     {
    13.         public MonitorController(AppSettings appSettings, ILogger logger, IWatcher watcher, RestClient restClient)
    14.         {
    15.             AppSettings = appSettings;
    16.             Logger = logger;
    17.             Watcher = watcher;
    18.             RestClient = restClient;
    19.         }
    20.  
    21.         public AppSettings AppSettings { get; }
    22.  
    23.         public ILogger Logger { get; }
    24.  
    25.         public IWatcher Watcher { get; }
    26.  
    27.         public RestClient RestClient { get; }
    28.  
    29.         public async Task ProcessAsync(ServiceWatchItem item)
    30.         {
    31.             while (true)
    32.             {
    33.                 try
    34.                 {
    35.                     Logger?.LogTrace("{0} - Watching '{1}' for '{2}' environment", DateTime.Now, item.ServiceName, item.Environment);
    36.  
    37.                     var watchResponse = await Watcher.WatchAsync(new WatcherParameter(item.ToDictionary()));
    38.  
    39.                     if (watchResponse.Success)
    40.                         Logger.LogInformation(" Success watch for '{0}' in '{1}' environment", item.ServiceName, item.Environment);
    41.                     else
    42.                         Logger.LogError(" Failed watch for '{0}' in '{1}' environment", item.ServiceName, item.Environment);
    43.  
    44.                     var watchLog = new ServiceStatusLog
    45.                     {
    46.                         ServiceID = item.ServiceID,
    47.                         ServiceEnvironmentID = item.ServiceEnvironmentID,
    48.                         Target = item.ServiceName,
    49.                         ActionName = Watcher.ActionName,
    50.                         Success = watchResponse.Success,
    51.                         Message = watchResponse.Message,
    52.                         StackTrace = watchResponse.StackTrace
    53.                     };
    54.  
    55.                     try
    56.                     {
    57.                         await RestClient.PostJsonAsync(AppSettings.ServiceStatusLogUrl, watchLog);
    58.                     }
    59.                     catch (Exception ex)
    60.                     {
    61.                         Logger.LogError(" Error on saving watch response ({0}): '{1}'", item.ServiceName, ex.Message);
    62.                     }
    63.                 }
    64.                 catch (Exception ex)
    65.                 {
    66.                     Logger.LogError(" Error watching service: '{0}': '{1}'", item.ServiceName, ex.Message);
    67.                 }
    68.  
    69.                 Thread.Sleep(item.Interval ?? AppSettings.DelayTime);
    70.             }
    71.         }
    72.     }
    73. }

    在运行控制台应用程序之前,请确保以下方面:

    1. ServiceMonitor 数据库可用
    2. ServiceMonitor 数据库具有服务类别,服务,服务观察者和用户的信息
    3. ServiceMonitor API可用

    我们可以检查url api/v1/Dashboard/ServiceWatcherItems的返回值:

    1.   "message":null,
    2.   "didError":false,
    3.   "errorMessage":null,
    4.   "model":[ 
    5.     { 
    6.       "serviceID":1,
    7.       "serviceEnvironmentID":1,
    8.       "environment":"Development",
    9.       "serviceName":"Northwind Database",
    10.       "interval":15000,
    11.       "url":null,
    12.       "address":null,
    13.       "connectionString":"server=(local);database=Northwind;user id=johnd;password=SqlServer2017$",
    14.       "typeName":"ServiceMonitor.Common.DatabaseWatcher, ServiceMonitor.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
    15.     },
    16.     { 
    17.       "serviceID":2,
    18.       "serviceEnvironmentID":3,
    19.       "environment":"Development",
    20.       "serviceName":"DNS",
    21.       "interval":3000,
    22.       "url":null,
    23.       "address":"192.168.1.1",
    24.       "connectionString":null,
    25.       "typeName":"ServiceMonitor.Common.PingWatcher, ServiceMonitor.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
    26.     },
    27.     { 
    28.       "serviceID":3,
    29.       "serviceEnvironmentID":4,
    30.       "environment":"Development",
    31.       "serviceName":"Sample API",
    32.       "interval":5000,
    33.       "url":"http://localhost:5612/api/values",
    34.       "address":null,
    35.       "connectionString":null,
    36.       "typeName":"ServiceMonitor.Common.HttpWebRequestWatcher, ServiceMonitor.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
    37.     }
    38.   ]
    39. }

    正如我们所看到的,API为DefaultUser返回所有服务,请记住关于一个用户可以订阅多个服务的概念,显然在此示例中,我们的默认用户被绑定到所有服务但我们可以在ServiceUser表中更改此链接。
    Program 类代码:

    1. using System;
    2. using System.Threading.Tasks;
    3. using Microsoft.Extensions.Configuration;
    4. using Microsoft.Extensions.Logging;
    5. using ServiceMonitor.Common;
    6. using ServiceMonitor.Common.Contracts;
    7.  
    8. namespace ServiceMonitor
    9. {
    10.     class Program
    11.     {
    12.         private static ILogger logger;
    13.         private static readonly AppSettings appSettings;
    14.  
    15.         static Program()
    16.         {
    17.             logger = LoggingHelper.GetLogger<Program>();
    18.  
    19.             var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
    20.  
    21.             var configuration = builder.Build();
    22.  
    23.             appSettings = new AppSettings
    24.             {
    25.                 ServiceWatcherItemsUrl = configuration["serviceWatcherItemUrl"],
    26.                 ServiceStatusLogUrl = configuration["serviceStatusLogUrl"],
    27.                 DelayTime = Convert.ToInt32(configuration["delayTime"])
    28.             };
    29.         }
    30.  
    31.         static void Main(string[] args)
    32.         {
    33.             StartAsync(args).GetAwaiter().GetResult();
    34.  
    35.             Console.ReadLine();
    36.         }
    37.  
    38.         static async Task StartAsync(string[] args)
    39.         {
    40.             logger.LogDebug("Starting application...");
    41.  
    42.             var initializer = new ServiceMonitorInitializer(appSettings);
    43.  
    44.             try
    45.             {
    46.                 await initializer.LoadResponseAsync();
    47.             }
    48.             catch (Exception ex)
    49.             {
    50.                 logger.LogError("Error on retrieve watch items: {0}", ex);
    51.                 return;
    52.             }
    53.  
    54.             try
    55.             {
    56.                 initializer.DeserializeResponse();
    57.             }
    58.             catch (Exception ex)
    59.             {
    60.                 logger.LogError("Error on deserializing object: {0}", ex);
    61.                 return;
    62.             }
    63.  
    64.             foreach (var item in initializer.Response.Model)
    65.             {
    66.                 var watcherType = Type.GetType(item.TypeName, true);
    67.  
    68.                 var watcherInstance = Activator.CreateInstance(watcherType) as IWatcher;
    69.  
    70.                 var task = Task.Factory.StartNew(async () =>
    71.                 {
    72.                     var controller = new MonitorController(appSettings, logger, watcherInstance, initializer.RestClient);
    73.  
    74.                     await controller.ProcessAsync(item);
    75.                 });
    76.             }
    77.         }
    78.     }
    79. }

    一旦我们检查了之前的方面,现在我们继续转向控制台应用程序,控制台输出是这样的:

    1. dbug: ServiceMonitor.Program[0]
    2.       Starting application
    3. sr trce: ServiceMonitor.Program[0]
    4.       06/20/2017 23:09:30 - Watching 'Sample API' for 'Development' environment
    5. trce: ServiceMonitor.Program[0]
    6.       06/20/2017 23:09:30 - Watching 'Northwind Database' for 'Development' environment
    7. trce: ServiceMonitor.Program[0]
    8.       06/20/2017 23:09:30 - Watching 'DNS' for 'Development' environment
    9. trce: ServiceMonitor.Program[0]
    10.       06/20/2017 23:09:35 - Watching 'DNS' for 'Development' environment
    11. trce: ServiceMonitor.Program[0]
    12.       06/20/2017 23:09:37 - Watching 'Sample API' for 'Development' environment
    13. trce: ServiceMonitor.Program[0]
    14.       06/20/2017 23:09:39 - Watching 'DNS' for 'Development' environment
    15. trce: ServiceMonitor.Program[0]
    16.       06/20/2017 23:09:42 - Watching 'DNS' for 'Development' environment
    17. trce: ServiceMonitor.Program[0]
    18.       06/20/2017 23:09:43 - Watching 'Sample API' for 'Development' environment
    19. trce: ServiceMonitor.Program[0]
    20.       06/20/2017 23:09:45 - Watching 'DNS' for 'Development' environment
    21. trce: ServiceMonitor.Program[0]
    22.       06/20/2017 23:09:47 - Watching 'Northwind Database' for 'Development' environment
    23. trce: ServiceMonitor.Program[0]
    24.       06/20/2017 23:09:48 - Watching 'Sample API' for 'Development' environment
    25. trce: ServiceMonitor.Program[0]
    26.       06/20/2017 23:09:48 - Watching 'DNS' for 'Development' environment
    27. trce: ServiceMonitor.Program[0]
    28.       06/20/2017 23:09:51 - Watching 'DNS' for 'Development' environment
    29. trce: ServiceMonitor.Program[0]
    30.       06/20/2017 23:09:53 - Watching 'Sample API' for 'Development' environment
    31. trce: ServiceMonitor.Program[0]
    32.       06/20/2017 23:09:54 - Watching 'DNS' for 'Development' environment
    33. trce: ServiceMonitor.Program[0]
    34.       06/20/2017 23:09:57 - Watching 'DNS' for 'Development' environment

    现在我们继续检查数据库中保存的数据,请检查ServiceEnvironmentStatus表,你会得到这样的结果:

    1. ServiceEnvironmentStatusID ServiceEnvironmentID Success WatchCount  LastWatch
    2. -------------------------- -------------------- ------- ----------- -----------------------
    3. 1                          4                    1       212         2018-11-22 23:11:34.113
    4. 2                          1                    1       78          2018-11-22 23:11:33.370
    5. 3                          3                    1       366         2018-11-22 23:11:34.620
    6.  
    7. (3 row(s) affected)

    它是如何一起工作的?控制台应用程序从API中监视所有服务,然后在MonitorController中以无限循环的方式为每个监视项启动一个任务,每个任务都有一个延迟时间,该间隔在服务定义中设置,但是如果没有为间隔定义值,间隔取自AppSettings; 因此,在执行Watch操作之后,结果将通过API保存在数据库中,并且该过程会自行重复。如果要watch对其他类型执行操作,可以创建自己的Watcher类。

友情链接
版权所有 Copyright(c)2004-2021 锐英源软件
公司注册号:410105000449586 豫ICP备08007559号 最佳分辨率 1024*768
地址:郑州大学北校区院(文化路97号院)内