通过计数器分析微服务性能

x33g5p2x  于2021-12-06 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(160)

介绍

.NET 计数器工具允许在 Visual Studio 中,随着时间将 dotnet core 应用程序的资源情况可视化,即通过统计图的方式呈现,可以查看系统在整个运行过程中的情况。

条件

.NET 计数器工具需要 Visual Studio 2019 版本 16.7 或者更高版本中使用,并程序版本是 .NET Core 3.0+ 或者更版本(.NET 5 、.NET 6 等),本篇博客以常用的 .NET Core 3.1 进行示例讲解。

教程

一、示例代码

就模拟经典的三层架构,来进行分析。首先创建 .NET Core 3.1 版本的 Web API 项目类型, 接着添加 ProductRepository、ProductService、HomeController 三个类,可以简单看做是个微服务的一个接口。

[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly ILogger<HomeController> _logger;

    private readonly ProductService _productService;
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _productService = new ProductService();
    }

    [HttpGet]
    public async Task<int> GetProductList()
    {
        var re = await _productService.GetProductListAsync();
        return re;
    }
}
public class ProductService
{
    private readonly ProductRepository _productRepository;
    public ProductService()
    {
        _productRepository = new ProductRepository();
    }

    public async Task<int> GetProductListAsync()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(1 * 100);
        });

        return await _productRepository.QueryProductListAsync();
    }
}
public class ProductRepository
{
    public async Task<int> QueryProductListAsync()
    {
        return await Task.Run(() =>
        {
            Thread.Sleep(1 * 100);
            return 1;
        });
    }
}

二、启动工具

代码写完后,在 Visual Studio 内按 Alt + F2 快捷键,可以看到如下界面,选择 .NET 计数器 ,然后点击开始。


点击开始后,计数器工具开始运行,程序是运行状态。当计数器工具最初收集数据时,可以看到 dotnet 计数器的实时值。还可以通过选中计数器名称旁边的复选框来查看计数器的统计图, 一次也可显示计数器多个资源的统计图。


接着,接着在浏览器对 http://localhost:43479/home 进行多次问(即:可以看做对微服务的即可进行访问)。


访问完成后,点击停止收集按钮即可

三、分析数据

在执行停止收集操作后,就可以查看 runtime 与 host 更详细的报表数据。上面的是根据时间的折线统计图,它会根据下面的一些复选框信息,勾选的进行时间线展示。

例如:runtime 可以看到 CPU Usage 最大、最小、平均使用率,折现图可以清晰的看到每个时间 CUP 使用情况。host 可以看到 Total Request (http 请求)情况,折线图也可以反应出每个时刻的请求情况。

相关文章

微信公众号

最新文章

更多