QueryModule.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. namespace Nancy.Benchmark
  2. {
  3. using System;
  4. using System.Data;
  5. using System.Threading.Tasks;
  6. using Dapper;
  7. using MySqlConnector;
  8. using Nancy;
  9. public class QueryModule : NancyModule
  10. {
  11. private readonly string ConnectionString;
  12. /**
  13. * Query:
  14. * Return a list of World objects as JSON, selected randomly from the World
  15. * table. Assume the table has 10,000 rows.
  16. */
  17. public QueryModule(IAppConfiguration appConfig) : base("/queries")
  18. {
  19. ConnectionString = appConfig.ConnectionString;
  20. Get("/{queries?1}", async args =>
  21. {
  22. if (!int.TryParse((string)args.queries, out var queries) || queries < 1)
  23. {
  24. queries = 1;
  25. }
  26. else if (queries > 500)
  27. {
  28. queries = 500;
  29. }
  30. var random = new Random();
  31. using (var db = new MySqlConnection(ConnectionString))
  32. {
  33. db.Open();
  34. // NOTE: Experiment with running the DB requests in parallel, on both Mono and Windows CLRs.
  35. var worlds = new World[queries];
  36. for (int i = 0; i < worlds.Length; ++i)
  37. {
  38. worlds[i] = await GetRandomWorld(db, random);
  39. }
  40. return Response.AsJson( worlds );
  41. }
  42. });
  43. Get("/{name}", async args =>
  44. {
  45. if (!int.TryParse((string)args.name, out var queries) || queries < 1)
  46. {
  47. queries = 1;
  48. }
  49. else if (queries > 500)
  50. {
  51. queries = 500;
  52. }
  53. var random = new Random();
  54. using (var db = new MySqlConnection(ConnectionString))
  55. {
  56. db.Open();
  57. // NOTE: Experiment with running the DB requests in parallel, on both Mono and Windows CLRs.
  58. var worlds = new World[queries];
  59. for (int i = 0; i < worlds.Length; ++i)
  60. {
  61. worlds[i] = await GetRandomWorld(db, random);
  62. }
  63. return Response.AsJson( worlds );
  64. }
  65. });
  66. }
  67. private Task<World> GetRandomWorld(IDbConnection db, Random random)
  68. {
  69. var id = random.Next(1, 10001);
  70. return db.QueryFirstOrDefaultAsync<World>("SELECT id, randomNumber FROM world WHERE id = @id", new { id });
  71. }
  72. }
  73. }