Advertisement
Old_But_Gold

Untitled

Nov 7th, 2024
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. using System.Text;
  2. using Newtonsoft.Json;
  3. using RabbitMQ.Client;
  4. using RabbitMQ.Client.Events;
  5.  
  6. namespace ChatMicroservice;
  7.  
  8. public class UserIdRequester
  9. {
  10. private readonly IConfiguration _configuration;
  11. private readonly ConnectionFactory _factory;
  12.  
  13. public UserIdRequester(IConfiguration configuration)
  14. {
  15. _configuration = configuration;
  16. _factory = _configuration.GetSection("RabbitMQ").Get<ConnectionFactory>()!;
  17. }
  18.  
  19. public async Task<Guid?> GetUserIdByUsernameAsync(string username)
  20. {
  21. using var connection = _factory.CreateConnection();
  22. using var channel = connection.CreateModel();
  23.  
  24. var requestQueue = "user_id_request_queue";
  25. //var replyQueue = "user_id_reply_queue";
  26.  
  27. //var correlationId = Guid.NewGuid().ToString();
  28.  
  29. //var props = channel.CreateBasicProperties();
  30.  
  31. //props.ReplyTo = replyQueue;
  32. //props.CorrelationId = correlationId;
  33.  
  34. channel.QueueDeclare(queue: requestQueue, durable: true, exclusive: false, autoDelete: false, arguments: null);
  35.  
  36. var message = new { Username = username };
  37. var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
  38.  
  39. channel.BasicPublish(exchange: string.Empty, routingKey: requestQueue, body: body);
  40.  
  41. /*var tcs = new TaskCompletionSource<Guid?>();
  42.  
  43. var consumer = new EventingBasicConsumer(channel);
  44. consumer.Received += (model, ea) =>
  45. {
  46. if (ea.BasicProperties.CorrelationId == correlationId)
  47. {
  48. var response = Encoding.UTF8.GetString(ea.Body.ToArray());
  49. if (Guid.TryParse(response, out var userId))
  50. {
  51. tcs.SetResult(userId);
  52. }
  53. else
  54. {
  55. tcs.SetResult(null);
  56. }
  57. }
  58. };
  59.  
  60. channel.BasicConsume(queue: replyQueue, autoAck: true, consumer: consumer);
  61. */
  62.  
  63. return null;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement