Program.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. [BeetleX.FastHttpApi.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 string ContentType => "application/json";
  48. public override bool HasBody => true;
  49. public override void Write(PipeStream stream, HttpResponse response)
  50. {
  51. using (stream.LockFree())
  52. {
  53. var task = JsonSerializer.NonGeneric.Utf8.SerializeAsync(Data, stream).AsTask();
  54. task.Wait();
  55. }
  56. }
  57. }
  58. public class BeetleXHttpServer : IHostedService
  59. {
  60. private HttpApiServer mApiServer;
  61. public virtual Task StartAsync(CancellationToken cancellationToken)
  62. {
  63. mApiServer = new HttpApiServer();
  64. mApiServer.Register(typeof(Program).Assembly);
  65. mApiServer.Options.Port = 8080;
  66. mApiServer.Options.BufferPoolMaxMemory = 500;
  67. mApiServer.Options.MaxConnections = 100000;
  68. mApiServer.Options.Statistical = false;
  69. mApiServer.Options.UrlIgnoreCase = false;
  70. mApiServer.Options.LogLevel = BeetleX.EventArgs.LogType.Off;
  71. mApiServer.Options.LogToConsole = true;
  72. mApiServer.Open();
  73. Console.WriteLine("BeetleX FastHttpApi server");
  74. Console.WriteLine($"ServerGC:{System.Runtime.GCSettings.IsServerGC}");
  75. Console.Write(mApiServer.BaseServer);
  76. return Task.CompletedTask;
  77. }
  78. public virtual Task StopAsync(CancellationToken cancellationToken)
  79. {
  80. mApiServer.BaseServer.Dispose();
  81. return Task.CompletedTask;
  82. }
  83. }
  84. }