Program.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using BeetleX.FastHttpApi;
  2. using Microsoft.Extensions.Hosting;
  3. using System.Threading.Tasks;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using System;
  6. using System.Threading;
  7. using System.Text;
  8. using BeetleX.Buffers;
  9. using SpanJson;
  10. namespace Benchmarks
  11. {
  12. [Controller]
  13. class Program
  14. {
  15. private static readonly byte[] _helloWorldPayload = Encoding.UTF8.GetBytes("Hello, World!");
  16. private static StringBytes plaintextResult;
  17. public static void Main(string[] args)
  18. {
  19. plaintextResult = new StringBytes(_helloWorldPayload);
  20. var builder = new HostBuilder()
  21. .ConfigureServices((hostContext, services) =>
  22. {
  23. services.AddHostedService<BeetleXHttpServer>();
  24. });
  25. builder.Build().Run();
  26. }
  27. public object plaintext(IHttpContext context)
  28. {
  29. return plaintextResult;
  30. }
  31. public object json(IHttpContext context)
  32. {
  33. return new SpanJsonResult(new JsonMessage { message = "Hello, World!" });
  34. }
  35. public class JsonMessage
  36. {
  37. public string message { get; set; }
  38. }
  39. }
  40. public class SpanJsonResult : ResultBase
  41. {
  42. public SpanJsonResult(object data)
  43. {
  44. Data = data;
  45. }
  46. public object Data { get; set; }
  47. public override IHeaderItem ContentType => ContentTypes.JSON;
  48. public override bool HasBody => true;
  49. public override void Write(PipeStream stream, HttpResponse response)
  50. {
  51. JsonSerializer.NonGeneric.Utf8.SerializeAsync(Data, stream);
  52. }
  53. }
  54. public class BeetleXHttpServer : IHostedService
  55. {
  56. private HttpApiServer mApiServer;
  57. public virtual Task StartAsync(CancellationToken cancellationToken)
  58. {
  59. mApiServer = new HttpApiServer();
  60. mApiServer.Register(typeof(Program).Assembly);
  61. mApiServer.Options.Port = 8080;
  62. mApiServer.Options.BufferPoolMaxMemory = 500;
  63. mApiServer.Options.MaxConnections = 100000;
  64. mApiServer.Options.Statistical = false;
  65. mApiServer.Options.UrlIgnoreCase = false;
  66. mApiServer.Options.LogLevel = BeetleX.EventArgs.LogType.Off;
  67. mApiServer.Options.LogToConsole = true;
  68. mApiServer.Options.IOQueueEnabled = true;
  69. mApiServer.Open();
  70. Console.WriteLine("BeetleX FastHttpApi server");
  71. Console.WriteLine($"ServerGC:{System.Runtime.GCSettings.IsServerGC}");
  72. Console.Write(mApiServer.BaseServer);
  73. return Task.CompletedTask;
  74. }
  75. public virtual Task StopAsync(CancellationToken cancellationToken)
  76. {
  77. mApiServer.BaseServer.Dispose();
  78. return Task.CompletedTask;
  79. }
  80. }
  81. }