| | 1 | | using System; |
| | 2 | | using Akka.Actor; |
| | 3 | | using Google.Protobuf; |
| | 4 | | using SeungYongShim.Kafka; |
| | 5 | |
|
| | 6 | | namespace SeungYongShim.Akka.OpenTelemetry.Kafka |
| | 7 | | { |
| | 8 | | public class KafkaProducerActor : ReceiveActor |
| | 9 | | { |
| 4 | 10 | | public record Message(IMessage Body, string Topic, string Key = "1"); |
| 1 | 11 | | public record Result(); |
| 0 | 12 | | public record ResultException(Exception Exception) : Result; |
| | 13 | |
|
| 1 | 14 | | public KafkaProducerActor(KafkaProducer kafkaProducer) |
| 1 | 15 | | { |
| 1 | 16 | | KafkaProducer = kafkaProducer; |
| | 17 | |
|
| 1 | 18 | | ReceiveAsync<Message>(async msg => |
| 2 | 19 | | { |
| 2 | 20 | | var sender = Sender; |
| 1 | 21 | |
|
| 1 | 22 | | try |
| 2 | 23 | | { |
| 2 | 24 | | await kafkaProducer.SendAsync(msg.Body, msg.Topic, msg.Key); |
| 2 | 25 | | sender.Tell(new Result()); |
| 2 | 26 | | } |
| 1 | 27 | | catch (Exception ex) |
| 1 | 28 | | { |
| 1 | 29 | | sender.Tell(new ResultException(ex)); |
| 1 | 30 | | } |
| 2 | 31 | | }); |
| 1 | 32 | | } |
| | 33 | |
|
| | 34 | | protected override void PostStop() |
| 1 | 35 | | { |
| 1 | 36 | | KafkaProducer.Dispose(); |
| 1 | 37 | | base.PostStop(); |
| 1 | 38 | | } |
| | 39 | |
|
| | 40 | | protected override void PreRestart(Exception reason, object message) |
| 0 | 41 | | { |
| 0 | 42 | | KafkaProducer.Dispose(); |
| 0 | 43 | | base.PreRestart(reason, message); |
| 0 | 44 | | } |
| | 45 | |
|
| | 46 | | public KafkaProducer KafkaProducer { get; } |
| | 47 | | } |
| | 48 | | } |