Program.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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.Open();
  69. Console.WriteLine("BeetleX FastHttpApi server");
  70. Console.WriteLine($"ServerGC:{System.Runtime.GCSettings.IsServerGC}");
  71. Console.Write(mApiServer.BaseServer);
  72. return Task.CompletedTask;
  73. }
  74. public virtual Task StopAsync(CancellationToken cancellationToken)
  75. {
  76. mApiServer.BaseServer.Dispose();
  77. return Task.CompletedTask;
  78. }
  79. }
  80. }