Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 6 mēnešiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Confluent.Kafka;
  2. using Microsoft.Extensions.Logging;
  3. using Microsoft.Extensions.Options;
  4. using Newtonsoft.Json;
  5. using TelpoPush.Models.Config;
  6. namespace TelpoPush.Service.Mq.Kafka
  7. {
  8. /// <summary>
  9. /// 消息生产者
  10. /// </summary>
  11. public class MessageProducer
  12. {
  13. private readonly ILogger<MessageProducer> _logger;
  14. private readonly ServiceConfig _configService;
  15. private readonly IProducer<Null, string> _producer;
  16. public MessageProducer(ILogger<MessageProducer> logger, IOptions<ServiceConfig> optConfigService)
  17. {
  18. _logger = logger;
  19. _configService = optConfigService.Value;
  20. var config = new ProducerConfig
  21. {
  22. BootstrapServers = _configService.KafkaBootstrapServers,
  23. EnableIdempotence = true,
  24. Acks = Acks.All,
  25. //LingerMs=5000,
  26. //BatchNumMessages =1000,
  27. //BatchSize=32768,
  28. //CompressionType= CompressionType.Lz4,
  29. MessageSendMaxRetries = 3
  30. };
  31. _producer = new ProducerBuilder<Null, string>(config).Build();
  32. }
  33. public Headers CreateHeader(Dictionary<string, int> pair = null)
  34. {
  35. if (pair == null)
  36. {
  37. return null;
  38. }
  39. else
  40. {
  41. Headers headers = new Headers();
  42. foreach (var item in pair)
  43. {
  44. headers.Add(item.Key, BitConverter.GetBytes(item.Value));
  45. }
  46. return headers;
  47. }
  48. }
  49. public async Task ProduceAsync(List<TopicModel> topic, object message)
  50. {
  51. try
  52. {
  53. foreach (var item in topic)
  54. {
  55. // producer = new ProducerBuilder<Null, string>(config).Build();
  56. await _producer.ProduceAsync(item.Topic, new Message<Null, string>
  57. {
  58. Headers = item.Headers,
  59. Value = JsonConvert.SerializeObject(message)
  60. });
  61. }
  62. }
  63. catch (ProduceException<Null, string> e)
  64. {
  65. _logger.LogError($"推送到kafka失败,topic: {topic},\n message:{JsonConvert.SerializeObject(message)}: \n{e.Error.Reason}");
  66. }
  67. }
  68. }
  69. }