【译】StackExchange.Redis 中文文档(十)性能分析

Profiling

性能分析 API 在版本 1.* 和版本 2.* 之间进行了重大更改;

在版本 1.*,特别是,object GetContext() API 对于消费者而言是不直观的,而对于库而言则是昂贵的。版本 2.* 中的 API 更简单,也更“明显”。这是一个巨大的变化。

下面介绍最新版本 2.*。关于版本 1.*,请点击查看原文。

StackExchange.Redis 公开了一些方法和类型来启用性能分析。由于其异步和多路复用行为,性能分析是一个有点复杂的话题。

接口

性能分析 API 由 ProfilingSession, ConnectionMultiplexer.RegisterProfiler(Func<ProfilingSession>),
ProfilingSession.FinishProfiling()IProfiledCommand 组成。

你注册了一个回调(Func<ProfilingSession>),该回调为环 境ProfilingSession 提供了一个 ConnectionMultiplexer 实例。在需要时,本类库将调用此回调,并且如果返回非空会话:操作将附加到该会话。在特定配置文件会话上调用 FinishProfiling 会返回 IProfiledCommand 的集合,其中包含已配置的 ConnectionMultiplexer 发送给 redis 的所有命令的时序信息。回调负责维护跟踪单个会话所需的任何状态。

可用时间

StackExchange.Redis 公开的信息包括:

  • The redis server involved
  • The redis DB being queried
  • The redis command run
  • The flags used to route the command
  • The initial creation time of a command
  • How long it took to enqueue the command
  • How long it took to send the command, after it was enqueued
  • How long it took the response from redis to be received, after the command was sent
  • How long it took for the response to be processed, after it was received
  • If the command was sent in response to a cluster ASK or MOVED response
    • If so, what the original command was

如果运行时支持 TimeSpan,那它有更高的辨识度。DateTimeDateTime.UtcNow 有同样的精度。

分析器示例

由于 StackExchange.Redis 的异步接口,分析需要外部帮助才能将相关命令组合在一起。这是通过回调提供所需的 ProfilingSession 对象,然后在该会话上调用 FinishProfiling() 来实现的。

可能最有用的通用会话提供程序是一种自动提供会话并在异步调用之间工作的程序。

class AsyncLocalProfiler
{
    private readonly AsyncLocal<ProfilingSession> perThreadSession = new AsyncLocal<ProfilingSession>();

    public ProfilingSession GetSession()
    {
        var val = perThreadSession.Value;
        if (val == null)
        {
            perThreadSession.Value = val = new ProfilingSession();
        }
        return val;
    }
}
...
var profiler = new AsyncLocalProfiler();
multiplexer.RegisterProfiler(profiler.GetSession);

这将为每个异步上下文自动创建一个分析会话(如果存在,则重新使用现有会话)。在某些工作单元结束时,调用代码可以使用 var commands = profiler.GetSession().FinishProfiling(); 来获取执行的操作和计时数据。


一个将许多不同线程发出的命令关联在一起的玩具示例(尽管仍然允许不分析无关的工作)

1.*

class ToyProfiler
{
    // note this won't work over "await" boundaries; "AsyncLocal" would be necessary there
    private readonly ThreadLocal<ProfilingSession> perThreadSession = new ThreadLocal<ProfilingSession>();
    public ProfilingSession PerThreadSession
    {
        get => perThreadSession.Value;
        set => perThreadSession.Value = value;
    }
}

// ...

ConnectionMultiplexer conn = /* initialization */;
var profiler = new ToyProfiler();
var sharedSession = new ProfilingSession();

conn.RegisterProfiler(() => profiler.PerThreadSession);

var threads = new List<Thread>();

for (var i = 0; i < 16; i++)
{
    var db = conn.GetDatabase(i);

    var thread =
        new Thread(
            delegate()
            {
                // set each thread to share a session
            	profiler.PerThreadSession = sharedSession;

                var threadTasks = new List<Task>();

                for (var j = 0; j < 1000; j++)
                {
                    var task = db.StringSetAsync("" + j, "" + j);
                    threadTasks.Add(task);
                }

                Task.WaitAll(threadTasks.ToArray());
            }
        );

	threads.Add(thread);
}

threads.ForEach(thread => thread.Start());
threads.ForEach(thread => thread.Join());

var timings = sharedSession.FinishProfiling();

最后,timings 将包含 16,000 个 IProfiledCommand 对象:每个对象发送 redis 一个命令。

如果相反,您执行以下操作:

ConnectionMultiplexer conn = /* initialization */;
var profiler = new ToyProfiler();

conn.RegisterProfiler(() => profiler.PerThreadSession);

var threads = new List<Thread>();

var perThreadTimings = new ConcurrentDictionary<Thread, List<IProfiledCommand>>();

for (var i = 0; i < 16; i++)
{
    var db = conn.GetDatabase(i);

    var thread =
        new Thread(
            delegate()
            {
                var threadTasks = new List<Task>();
                profiler.PerThreadSession = new ProfilingSession();

                for (var j = 0; j < 1000; j++)
                {
                    var task = db.StringSetAsync("" + j, "" + j);
                    threadTasks.Add(task);
                }

                Task.WaitAll(threadTasks.ToArray());

                perThreadTimings[Thread.CurrentThread] = profiler.PerThreadSession.FinishProfiling().ToList();
            }
        );
    threads.Add(thread);
}

threads.ForEach(thread => thread.Start());
threads.ForEach(thread => thread.Join());

perThreadTimings 最终有 16 个包含 1000 个 IProfilingCommand 的对象,并由 Thread 作为键。

这是在 MVC5 应用程序中配置 StackExchange.Redis 的方法。

首先在 ConnectionMultiplexer 中注册以下 IProfiler

public class RedisProfiler
{
    const string RequestContextKey = "RequestProfilingContext";

    public ProfilingSession GetSession()
    {
        var ctx = HttpContext.Current;
        if (ctx == null) return null;

        return (ProfilingSession)ctx.Items[RequestContextKey];
    }

    public void CreateSessionForCurrentRequest()
    {
        var ctx = HttpContext.Current;
        if (ctx != null)
        {
            ctx.Items[RequestContextKey] = new ProfilingSession();
        }
    }
}

然后,将以下内容添加到 Global.asax.cs 文件中(其中 _redisProfiler 是分析器的实例):

protected void Application_BeginRequest()
{
    _redisProfiler.CreateSessionForCurrentRequest();
}

protected void Application_EndRequest()
{
    var session = _redisProfiler.GetSession();
    if (session != null)
    {
        var timings = session.FinishProfiling();

		// do what you will with `timings` here
    }
}

并确保在创建连接时连接已注册了分析器:

connection.RegisterProfiler(() => _redisProfiler.GetSession());

此实现会将所有 redis 命令(包括 async/await)与启动它们的http请求进行分组。

原文地址:Profiling

原文地址:https://www.cnblogs.com/liang24/p/13847240.html