您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

MessageProcessingMqttConnectionContextBenchmark.cs 2.2 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Client;
  3. using MQTTnet.AspNetCore;
  4. using Microsoft.AspNetCore;
  5. using Microsoft.AspNetCore.Hosting;
  6. using MQTTnet.Server;
  7. using MQTTnet.Diagnostics;
  8. using MQTTnet.AspNetCore.Client;
  9. namespace MQTTnet.Benchmarks
  10. {
  11. [MemoryDiagnoser]
  12. public class MessageProcessingMqttConnectionContextBenchmark
  13. {
  14. private IWebHost _host;
  15. private IMqttClient _mqttClient;
  16. private MqttApplicationMessage _message;
  17. [GlobalSetup]
  18. public void Setup()
  19. {
  20. _host = WebHost.CreateDefaultBuilder()
  21. .UseKestrel(o => o.ListenAnyIP(1883, l => l.UseMqtt()))
  22. .ConfigureServices(services => {
  23. var mqttServerOptions = new MqttServerOptionsBuilder()
  24. .WithoutDefaultEndpoint()
  25. .Build();
  26. services
  27. .AddHostedMqttServer(mqttServerOptions)
  28. .AddMqttConnectionHandler();
  29. })
  30. .Configure(app => {
  31. app.UseMqttServer(s => {
  32. });
  33. })
  34. .Build();
  35. var factory = new MqttFactory();
  36. _mqttClient = factory.CreateMqttClient(new MqttNetLogger(), new MqttClientConnectionContextFactory());
  37. _host.StartAsync().GetAwaiter().GetResult();
  38. var clientOptions = new MqttClientOptionsBuilder()
  39. .WithTcpServer("localhost").Build();
  40. _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult();
  41. _message = new MqttApplicationMessageBuilder()
  42. .WithTopic("A")
  43. .Build();
  44. }
  45. [GlobalCleanup]
  46. public void Cleanup()
  47. {
  48. _mqttClient.DisconnectAsync().GetAwaiter().GetResult();
  49. _mqttClient.Dispose();
  50. _host.StopAsync().GetAwaiter().GetResult();
  51. _host.Dispose();
  52. }
  53. [Benchmark]
  54. public void Send_10000_Messages()
  55. {
  56. for (var i = 0; i < 10000; i++)
  57. {
  58. _mqttClient.PublishAsync(_message).GetAwaiter().GetResult();
  59. }
  60. }
  61. }
  62. }