Exemple #1
0
        public async Task <IActionResult> Issue(string quoteId, [FromBody] object content)
        {
            try
            {
                var policyNumber = GeneratePolicyNumber();
                var request      = JObject.Parse(content.ToString());
                request["policyNumber"] = policyNumber;

                Console.WriteLine("request content here - " + content);

                var mongo = new MongoConnector(MongoConnectionString, MONGO_DB_NAME);

                mongo.InsertData(MONGO_PolicyIssue_Collection, request);

                var policyObject = mongo.GetPolicyObject(quoteId);

                policyObject.Add(new JProperty("policyNumber", policyNumber));
                policyObject.Add(new JProperty("issue-info", request));

                var message = await KafkaService.SendMessage(policyObject.ToString(), _logger);

                //var message = "success";
                PolicyData.Add(policyObject.ToString());
                var finalResult = new JObject(new JProperty("policyNumber", policyNumber), new JProperty("result", new JObject(new JProperty("status", message), new JProperty("policy", policyObject))));
                return(Ok(finalResult.ToString()));
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(Ok());
            }
        }
Exemple #2
0
        public PrinterActor(KafkaService _kafkaService)
        {
            kafkaService = _kafkaService;

            id = Guid.NewGuid().ToString();
            logger.Info($"프린터 액터 생성:{id}");

            //주소로 액터를 선택하기 : 위치투명성,참조객체를 얻기위해 DI가 복잡해질필요 없다,그리고 이것은 리모트로확장시 코드변화가없다.
            tonerActor = Context.System.ActorSelection("user/toner");

            ReceiveAsync <PrintPage>(async page =>
            {
                logger.Debug($"프린터 요청 들어옴:{page}");
                await Task.Delay(page.DelayForPrint);


                //토너를 비동기로 소모시킴
                tonerActor.Tell(1);

                //남은 토너 용량 물어봄
                var msg = await tonerActor.Ask("남은용량?");
                if (null != Sender)
                {
                    Sender.Tell(msg);
                }

                logger.Debug($"ASK결과:{msg}");
                logger.Debug($"페이지 출력 완료:{page}");
            });

            ReceiveAsync <string>(async msg =>
            {
                logger.Debug($"토너 관리액터에게 받은 메시지:{msg}");
            });
        }
 public HomeController(KafkaService <Log> logKafkaService, KafkaService <Order> orderKafkaService, ILogger <HomeController> logger, IOptionsMonitor <KafkaOptions> kafkaOptionsAccesstor)
 {
     _logKafkaService   = logKafkaService;
     _orderKafkaService = orderKafkaService;
     _logger            = logger;
     _kafkaOptions      = kafkaOptionsAccesstor.CurrentValue;
 }
Exemple #4
0
 public CopyCommand(KafkaService kafkaService)
     : base("copy", "Transfers messages from one topic to another")
 {
     _kafkaService = kafkaService;
     PrepareCommand();
     Handler = CommandHandler
               .Create <string, string, string, AutoOffsetReset, string, string, CancellationToken>(Handle);
 }
Exemple #5
0
 static void Main(string[] args)
 {
     while (true)
     {
         KafkaService.InvokeService().Wait();
     }
     Console.ReadLine();
 }
Exemple #6
0
 public ConsumeCommand(KafkaService kafkaService)
     : base("consume", "Consumes messages from a topic")
 {
     _kafkaService = kafkaService;
     PrepareCommand();
     Handler = CommandHandler
               .Create <string, string, string, AutoOffsetReset, CancellationToken>(Handle);
 }
 public HttpResponseMessage PostResource([FromBody] ResourceWithValue model)
 {
     try
     { ResourceRepository.AddResourceInfo(model);
       KafkaService.PostResource(model);
       return(Request.CreateResponse(System.Net.HttpStatusCode.OK, 202)); }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex));
     }
 }
 public HttpResponseMessage GetResource([FromUri] long?id)
 {
     try
     {
         List <ResourceWithValue> resourceList = ResourceRepository.GetResourceInfo(id);
         List <ResourceWithValue> rsList       = KafkaService.GetResource(id);
         return(Request.CreateResponse(System.Net.HttpStatusCode.OK, resourceList));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, "Server - Error Fetching resource Information"));
     }
 }
Exemple #9
0
        private static RootCommand BuildRootCommand()
        {
            var cmd          = new RootCommand();
            var kafkaService = new KafkaService();
            var copyCommand  = new CopyCommand(kafkaService);

            cmd.AddCommand(copyCommand);

            var consumeCommand = new ConsumeCommand(kafkaService);

            cmd.AddCommand(consumeCommand);

            return(cmd);
        }
Exemple #10
0
        public async Task <int> OnExecuteAsync(KafkaService kafkaService, IReporter reporter, ILogger <ProduceCommand> logger)
        {
            try
            {
                await kafkaService.ProduceContent(Topic, Path);

                return(0);
            }
            catch (Exception ex)
            {
                reporter.Error(ex.Message);
                logger.LogError(ex, nameof(OnExecuteAsync));
                return(1);
            }
        }
Exemple #11
0
        static async Task Main(string[] args)
        {
            var kafkaService = new KafkaService();

            //Console.WriteLine("Using: start with '-E' for Event or '-M' for message");
            //Console.WriteLine("Using: add '-O' to send for One instance or '-A' to send for All available instances");
            //Console.WriteLine("Example: -M -A Hi all");
            //Console.WriteLine("By default chooses -M and -O");
            Console.WriteLine("Enter message");

            while (true)
            {
                var inputMessage = Console.ReadLine();

                if (inputMessage.StartsWith("-M -A"))
                {
                    await kafkaService.SendMessageAsync("testTopic", inputMessage.Substring(6));
                }
                if (inputMessage.StartsWith("-M -O"))
                {
                    await kafkaService.SendMessageAsync("testTopic", inputMessage.Substring(6));
                }
                if (inputMessage.StartsWith("-E -O"))
                {
                    await kafkaService.SendEventAsync("testTopic", inputMessage.Substring(6));
                }
                if (inputMessage.StartsWith("-E -A"))
                {
                    await kafkaService.SendEventAsync("testTopic", inputMessage.Substring(6));
                }
                else
                {
                    await kafkaService.SendMessageAsync("testTopic", inputMessage);
                }
            }

            Console.WriteLine("Producer stopped");
        }
 public LogConsumerBackgroundService(KafkaService <Log> kafkaService, ILogger <LogConsumerBackgroundService> logger)
 {
     _kafkaService = kafkaService;
     _logger       = logger;
 }
Exemple #13
0
 public OrderController(IConfiguration configuration)
 {
     _kafkaService = new KafkaService(configuration);
 }
Exemple #14
0
        public async Task Kafka_Test_1()
        {
            var          locator = new KafkaLocator();
            KafkaService service = await locator.Locate();

            const string topicName = "unit-test";
            var          config    = new Dictionary <string, object>
            {
                { "group.id", "unit-test-1" },
                { "auto.offset.reset", "earliest" }
            };

            bool done = false;

            using (var consumer = service.GetConsumer(config, new StringDeserializer(Encoding.UTF8)))
            {
                consumer.OnPartitionEOF += (_, end)
                                           => Console.WriteLine($"Reached end of topic {end.Topic} partition {end.Partition}, next message will be at offset {end.Offset}");

                consumer.OnError += (_, error)
                                    => Console.WriteLine($"Error: {error}");

                consumer.OnPartitionsAssigned += (_, partitions) =>
                {
                    Console.WriteLine($"Assigned partitions: [{string.Join(", ", partitions)}], member id: {consumer.MemberId}");
                    consumer.Assign(partitions);
                };

                consumer.OnPartitionsRevoked += (_, partitions) =>
                {
                    Console.WriteLine($"Revoked partitions: [{string.Join(", ", partitions)}]");
                    consumer.Unassign();
                };

                consumer.OnStatistics += (_, json)
                                         => Console.WriteLine($"Statistics: {json}");

                consumer.Subscribe(topicName);

                Task consumerTask = Task.Run(() =>
                {
                    while (!done)
                    {
                        if (consumer.Consume(out Message <Null, string> msg, TimeSpan.FromSeconds(1)))
                        {
                            Console.WriteLine($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                            consumer.CommitAsync(msg).Wait();
                        }
                    }
                });

                await Task.Delay(2000);

                using (var producer = service.GetProducer(new StringSerializer(Encoding.UTF8)))
                {
                    Console.WriteLine($"{producer.Name} producing on {topicName}.");
                    for (int i = 22; i > 0; i--)
                    {
                        await producer.ProduceAsync(topicName, null, Guid.NewGuid().ToString());
                    }

                    producer.Flush(TimeSpan.FromSeconds(10));
                }

                done = true;
                await consumerTask;
            }
        }
Exemple #15
0
 public async System.Threading.Tasks.Task <string> publishAsync([FromBody] object requestBody)
 {
     _logger.LogInformation("Service called for publish");
     return(await KafkaService.SendMessage(requestBody.ToString(), _logger));
 }
 public ProcessOrderBackgroundService(IConfiguration configuration, IServiceScopeFactory serviceScopeFactory, ILogger <ProcessOrderBackgroundService> logger)
 {
     _kafkaService        = new KafkaService(configuration);
     _serviceScopeFactory = serviceScopeFactory;
     _logger = logger;
 }
        static async Task Main(string[] args)
        {
            var kafkaService = new KafkaService();

            kafkaService.SubscribeAsync <string>("testTopic", HandleEvent, HandleBy.OneInstance);
        }