public RabbitProducerTests() { IServiceProvider serviceProvider = FakeConfig.BuildServiceProvider(); serializer = serviceProvider.GetRequiredServiceByName <ISerializer>(FakeConfig.Options.SerializationType); producer = new RabbitProducer(serviceProvider, FakeConfig.ProviderName, serializer); }
private void customButton1_Click(object sender, EventArgs e) { RabbitProducer <string> producer = new RabbitProducer <string>("MiriTest"); producer.SendMessage("TEST1"); ShowMessage("All sent"); }
public static void LogProducerQueueProcessingCanceled( this ISilverbackLogger logger, RabbitProducer producer) => ProducerQueueProcessingCanceled( logger.InnerLogger, producer.Id, producer.Endpoint.DisplayName, null);
public TransactionRequestListener(IEventStoreConnection eventStoreConnection, IMongoDatabase mongoDatabase, IConfiguration configuration) : base("transactionsExchange", "transactionsQueue", "transactions.new", new RabbitConfig(configuration)) { _eventStoreConnection = eventStoreConnection; _mongoDatabase = mongoDatabase; _producer = new RabbitProducer(new RabbitConfig(configuration)); }
static int Main(string[] args) { RabbitProducer producer = new RabbitProducer(); producer.Connect(); producer.SendMessages(); producer.Disconnect(); Console.WriteLine("All sent."); return 0; //Console.ReadLine(); }
/// <summary> /// 创建生产者 /// </summary> /// <param name="queueOrOtherIdentify">队列或其他标识</param> /// <param name="messageQueueInfoFactory">消息队列信息工厂</param> /// <returns>生产者</returns> public IProducer CreateProducer(string queueOrOtherIdentify, IMessageQueueInfoFactory messageQueueInfoFactory) { ValidateUtil.ValidateNull(messageQueueInfoFactory, "消息队列信息工厂"); ValidateConnection(); IProducer producer = new RabbitProducer(CreateChannel(), queueOrOtherIdentify, messageQueueInfoFactory, virtualPath: virtualPath); AddClosedEventHandler(producer); return(producer); }
/// <summary> /// 创建生产者 /// </summary> /// <param name="messageQueueInfo">消息队列信息</param> /// <returns>生产者</returns> public IProducer CreateProducer(MessageQueueInfo messageQueueInfo) { ValidateUtil.ValidateNull(messageQueueInfo, "Rabbit消息队列信息"); ValidateConnection(); IProducer producer = new RabbitProducer(CreateChannel(), RabbitMessageQueueInfo.From(messageQueueInfo)); AddClosedEventHandler(producer); return(producer); }
/// <summary> /// 创建生产者 /// </summary> /// <param name="messageQueueInfoFactory">消息队列信息工厂</param> /// <returns>生产者</returns> public IProducer CreateProducer(IMessageQueueInfoFactory messageQueueInfoFactory) { ValidateUtil.ValidateNull(messageQueueInfoFactory, "消息队列信息工厂"); ValidateConnection(); IProducer producer = new RabbitProducer(CreateChannel(), messageQueueInfoFactory); AddClosedEventHandler(producer); return(producer); }
// Agent 업무처리 private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) { msg_cnt++; txtStatusBar.Text = msg_cnt + "건 처리중"; MqRecvVo mrvo = (MqRecvVo)e.UserState; logger.Debug("ProgressChanged req_typ : " + mrvo.req_typ); if (mrvo.req_typ == "HLTH") { MqSendHealthVo msVo = new MqSendHealthVo(); msVo.agent_id = mrvo.agent_id; msVo.agent_status = RabbitConsumer.AgentStatus; msVo.res_typ = mrvo.req_typ; RabbitProducer.Connect(); RabbitProducer.MqSendMessages(mrvo.agent_id, msVo.toJson()); RabbitProducer.Disconnect(); logger.Debug("agent_id : " + msVo.agent_id); } else { //실행시작 MqSendVo msVo = new MqSendVo(); msVo.res_typ = "RLT"; msVo.agent_id = mrvo.agent_id; msVo.agent_status = "BUSY"; msVo.job_status = "ING"; msVo.rlt_data = ""; msVo.exec_req_id = mrvo.exec_req_id; logger.Debug("ProgressChanged exec start : " + msVo.toJson()); RabbitConsumer.AgentStatus = msVo.agent_status; logger.Debug("ProgressChanged AgentStatus : " + RabbitConsumer.AgentStatus); //상태변경 RabbitProducer.Connect(); RabbitProducer.MqSendMessages(mrvo.agent_id, msVo.toJson()); RabbitProducer.Disconnect(); // 작업실행 String result = AgentExecutor.Execute(mrvo.req_typ, mrvo.req_data, mrvo.job_tmout); msVo.agent_status = "IDLE"; msVo.job_status = "CMP"; msVo.rlt_data = result; logger.Debug("ProgressChanged exec result : " + msVo.toJson()); RabbitConsumer.AgentStatus = msVo.agent_status; logger.Debug("ProgressChanged AgentStatus : " + RabbitConsumer.AgentStatus); //결과전송 RabbitProducer.Connect(); RabbitProducer.MqSendMessages(mrvo.agent_id, msVo.toJson()); RabbitProducer.Disconnect(); } txtStatusBar.Text = msg_cnt + "건 처리완료"; }
public void QueueTest() { int counter = 0; string queue = $"integration.{queue1}"; //消费 var consumer = new RabbitConsumer(hosts) { Password = password, Port = port, UserName = userName, VirtualHost = virtualHost }; consumer.Listen(queue, new ConsumeQueueOptions() { Arguments = arguments, AutoAck = false, AutoDelete = true, Durable = true, FetchCount = 1 }, result => { Output.WriteLine($"{queue}:" + result.Body); counter++; result.Commit(); }); //发布 var producer = new RabbitProducer(hosts) { Password = password, Port = port, UserName = userName, VirtualHost = virtualHost }; producer.Publish(queue, "hello queue", new QueueOptions() { Arguments = arguments, AutoDelete = true, Durable = true }); BlockUntil(() => counter >= 1, 3000); producer.Dispose(); consumer.Dispose(); Assert.Equal(1, counter); }
// // same as above, but will be expecting a Dictionary (Dictionary is prefered over Hashtable) // for those cases where we aren't already building a log - and do not need to save it to the log collection // this will let us use anything and toss it to rabbit // key is appended to parkingPass. to create the route key. We typically use "log", but could be something else public bool sendToRabbitMQ(string key, Dictionary <string, string> log) { try { RabbitProducer rabbitProducer = new RabbitProducer(); var serializer = new JavaScriptSerializer(); string payload = serializer.Serialize(log); return(rabbitProducer.createMessage(key, payload)); } catch { return(false); } }
public override void OnGetMessageFromGenerator(string strMessage) { string queueToMQGeneratorName = ConfigurationManager.AppSettings["QueueToMQGeneratorName"]; RabbitProducer <string> producer = new RabbitProducer <string>(queueToMQGeneratorName); SendMQMessage message = JsonConvert.DeserializeObject <SendMQMessage>(strMessage); Metaquery metaquery = new Metaquery(message); ResultMQ resultMQ = ResultMQ.HasAnswers; // Random the probability of the result Random rnd = new Random(); int rndSupport = rnd.Next(100); //Probability of support failure if (rndSupport < SupportProbability) { resultMQ = ResultMQ.SupportFailure; } else { //Probability of confidence failure int rndConfidence = rnd.Next(100); if (rndConfidence < ConfidenceProbability) { resultMQ = ResultMQ.ConfidenceFailure; } } MQResultMessage resultMessage = new MQResultMessage() { ID = message.ID, Result = resultMQ }; if (resultMQ == ResultMQ.HasAnswers) { MQAssignmentResultMessage assignmentResultMessage = new MQAssignmentResultMessage() { ID = message.ID, Assignment = "TEST - Assignment", ConfidenceValue = 0, SupportValue = 0 }; SendMQMessageToSolver(producer, assignmentResultMessage); } SendMQMessageToSolver(producer, resultMessage); }
/// <summary> /// 租赁一个发布者 /// </summary> /// <returns></returns> public RabbitProducer RentProducer() { if (Disposed) { throw new ObjectDisposedException(nameof(RabbitClientProducer)); } RabbitProducer rabbitProducer; lock (rabbitProducers) { if (!rabbitProducers.TryDequeue(out rabbitProducer) || rabbitProducer == null || !rabbitProducer.IsOpen) { rabbitProducer = RabbitProducer.Create(rabbitOptions); } } return(rabbitProducer); }
/// <summary> /// 返回保存发布者 /// </summary> /// <param name="rabbitProducer"></param> public void ReturnProducer(RabbitProducer rabbitProducer) { if (Disposed) { return; } lock (rabbitProducers) { if (rabbitProducers.Count < InitializeCount && rabbitProducer != null && rabbitProducer.IsOpen) { rabbitProducers.Enqueue(rabbitProducer); } else { rabbitProducer?.Dispose(); } } }
private void startMq(String ageintId) { RabbitConsumer.Connect(ageintId); RabbitConsumer.ConsumeMessagesStart(ageintId); bgAgentWorker = new BackgroundWorker(); //ReportProgress메소드를 호출하기 위해서 반드시 true로 설정, false일 경우 ReportProgress메소드를 호출하면 exception 발생 bgAgentWorker.WorkerReportsProgress = true; //스레드에서 취소 지원 여부 bgAgentWorker.WorkerSupportsCancellation = true; //스레드가 run시에 호출되는 핸들러 등록 bgAgentWorker.DoWork += new DoWorkEventHandler(bw_DoWork); // ReportProgress메소드 호출시 호출되는 핸들러 등록 bgAgentWorker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); // 스레드 완료(종료)시 호출되는 핸들러 동록 bgAgentWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); bgAgentWorker.RunWorkerAsync(); /* Mq 수신 시작 알림 */ MqSendHealthVo msVo = new MqSendHealthVo(); msVo.agent_id = ageintId; msVo.agent_status = "IDLE"; msVo.res_typ = "RES"; RabbitProducer.Connect(); RabbitProducer.MqSendMessages(ageintId, msVo.toJson()); RabbitProducer.Disconnect(); logger.Info("agent_id : " + msVo.agent_id + " IDLE.. "); startAgent.Text = "STOP"; this.Visible = false; trayIcon.Visible = true; }
private void StartAgent_Click(object sender, EventArgs e) { if (startAgent.Text == "STOP") { DialogResult dr = MessageBox.Show("통선임RPA를 중지할까요?", "통선임RPA", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { bgAgentWorker.CancelAsync();//백그라운드작업 취소 startAgent.Text = "START"; /* Mq 수신 시작 알림 */ MqSendHealthVo msVo = new MqSendHealthVo(); msVo.agent_id = AgentId.Text; msVo.agent_status = "DOWN"; msVo.res_typ = "RES"; RabbitProducer.Connect(); RabbitProducer.MqSendMessages(AgentId.Text, msVo.toJson()); RabbitProducer.Disconnect(); logger.Info("agent_id : " + msVo.agent_id + " DOWN ..... "); } return; } // Agent ID 조회 Agent aginfo = AgentService.getAgentInfo(MacAddr.Text); if (aginfo == null) { MessageBox.Show("Mac주소를 확인하세요"); return; } AgentId.Text = aginfo.agent_id; logger.Debug(". :" + AgentId.Text); startMq(AgentId.Text); }
private static void Init() { Types[typeof(IProducer)] = new RabbitProducer(); Types[typeof(IConsumer)] = new RabbitConsumer(); isInit = true; }
//public static void SendMQAssignmentResultMessage(RabbitProducer<string> producer, MQAssignmentResultMessage resultMessage) //{ // string strMessage = resultMessage.ToJson(); // producer.SendMessage(strMessage); //} public virtual void OnGetMessageFromGenerator(string strMessage) { string queueToMQGeneratorName = ConfigurationManager.AppSettings["QueueToMQGeneratorName"]; RabbitProducer <string> producer = new RabbitProducer <string>(queueToMQGeneratorName); SendMQMessage message = JsonConvert.DeserializeObject <SendMQMessage>(strMessage); Metaquery metaquery = new Metaquery(message); List <ResultDemoMq> resultMQList = MetaquerySolverDemoDS.GetResultDemoMq(metaquery.ToString()); bool hasResult = resultMQList.Count > 0; ResultMQ resultMQ = ResultMQ.HasAnswers; if (!hasResult) { Random rnd = new Random(); int rndNum = rnd.Next(2); if (rndNum == 0) { resultMQ = ResultMQ.ConfidenceFailure; } else { resultMQ = ResultMQ.SupportFailure; } } MQResultMessage resultMessage = new MQResultMessage() { ID = message.ID, Result = resultMQ }; if (hasResult) { foreach (ResultDemoMq resultDemoMQ in resultMQList) { MQAssignmentResultMessage assignmentResultMessage = new MQAssignmentResultMessage() { ID = message.ID, Assignment = resultDemoMQ.Assignment, ConfidenceValue = resultDemoMQ.ConfidenceValue.Value, SupportValue = resultDemoMQ.SupportValue.Value }; SendMQMessageToSolver(producer, assignmentResultMessage); //System.Threading.Thread.Sleep(3000); } } SendMQMessageToSolver(producer, resultMessage); //System.Threading.Thread.Sleep(3000); /* * MQResultMessage resultMessage = new MQResultMessage() { ID = 1, Result = true}; * * string strMessage = JsonConvert.SerializeObject(resultMessage); * string strResultMessageJson = "{\"ID\":1,\"Result\":true}"; * Assert.AreEqual(strMessage, strResultMessageJson); * * MQAssignmentResultMessage assignmentResultMessage = new MQAssignmentResultMessage() { ID = 1,Assignment="Any assignment",ConfidenceValue=0.3f,SupportValue=0.1f }; * strMessage = JsonConvert.SerializeObject(assignmentResultMessage); * strResultMessageJson = "{\"ID\":1,\"SupportValue\":0.1,\"ConfidenceValue\":0.3,\"Assignment\":\"Any assignment\"}"; */ //MessageBox.Show("TestEvent, string: " + result.Metaquery); }
public static void SendMQMessageToSolver(RabbitProducer <string> producer, MQMessage resultMessage) { string strMessage = resultMessage.ToJson(); producer.SendMessage(strMessage); }
public static int StartSendMQToSolver() { List <TblMetaquery> lstMQ = MetaqueryDS.GetMQForSendToSolver(); int count = 0; bool doStartExpandMQProcess = false, doStartIncreaseDBArity = false; while (lstMQ.Count > 0) { RabbitProducer <string> producer = null; foreach (TblMetaquery tblMetaquery in lstMQ) { TblDatabaseManagement curDB = tblMetaquery.TblDatabaseManagement; if (!curDB.ForExperiment) { if (producer == null) { string queueToMQSolverName = ConfigurationManager.AppSettings["QueueToMQSolverName"]; producer = new RabbitProducer <string>(queueToMQSolverName); } Metaquery metaquery = new Metaquery(tblMetaquery.Metaquery); //שליחה לסולבר SendMQMessage message = new SendMQMessage() { ID = tblMetaquery.Id, SupportThreshold = curDB.SupportThreshold, ConfidenceThreshold = curDB.ConfidenceThreshold, Head = metaquery.Head.Variables, Body = metaquery.Body.GetVariables() }; string strMessage = message.ToJson(); //JsonConvert.SerializeObject(message); producer.SendMessage(strMessage); MetaqueryDS.UpdateStatus(tblMetaquery, StatusMQ.WaitingToSolver); } else { RandomMQProbability randomMQProbability = new RandomMQProbability(curDB.SupportProbability.Value, curDB.ConfidenceProbability.Value, curDB.ProbabilityIncreaseByArity ?? 0, tblMetaquery.Arity); tblMetaquery.FkResult = (int)randomMQProbability.GetRandomResultMQ(); StatusMQ statusMQ = (tblMetaquery.IsExpanded || tblMetaquery.Arity == tblMetaquery.TblDatabaseManagement.MaxArity ? StatusMQ.Done : StatusMQ.WaitingToExpand); MetaqueryDS.UpdateStatus(tblMetaquery, statusMQ); if (statusMQ == StatusMQ.WaitingToExpand) { doStartExpandMQProcess = true; } else if (statusMQ == StatusMQ.Done) { doStartIncreaseDBArity = true; } } count++; } lstMQ = MetaqueryDS.GetMQForSendToSolver(); } if (MQGenerator.IsAutoRunJobs) { if (doStartExpandMQProcess) { MQGenerator.StartExpandMQProcess(); } else if (doStartIncreaseDBArity) { MQGenerator.StartIncreaseDBArity(); } } return(count); }
public void DirectExchangeTest() { Dictionary <string, int> dict = new Dictionary <string, int>(); //接收的消息数量 Dictionary <string, int> expectedDict = new Dictionary <string, int>(); //发送的消息数量 string[] queues = new string[] { $"integration.{queue1}.direct", $"integration.{queue2}.direct" }; var routeQueues = queues.Select(f => new RouteQueue() { Arguments = null, Queue = f, Route = f, Options = new QueueOptions() { AutoDelete = true, Durable = true, Arguments = arguments } }).ToArray(); //消费 var consumer = new RabbitConsumer(hosts) { Password = password, Port = port, UserName = userName, VirtualHost = virtualHost }; foreach (var queue in queues) { dict[queue] = 0; expectedDict[queue] = 0; consumer.Listen(direct, queue, new ExchangeConsumeQueueOptions() { Arguments = arguments, AutoAck = false, AutoDelete = true, Durable = true, FetchCount = 1, RouteQueues = routeQueues, Type = RabbitExchangeType.Direct }, result => { Output.WriteLine($"{queue}:" + result.Body); dict[queue]++; result.Commit(); }); } //发布 var producer = new RabbitProducer(hosts) { Password = password, Port = port, UserName = userName, VirtualHost = virtualHost }; for (var i = 0; i < queues.Length; i++) { var queue = queues[i]; expectedDict[queue]++; producer.Publish(direct, queue, "direct" + i, new ExchangeQueueOptions() { Arguments = arguments, AutoDelete = true, Durable = true, RouteQueues = routeQueues, Type = RabbitExchangeType.Direct }); } BlockUntil(() => dict.Sum(f => f.Value) >= queues.Length, 3000); producer.Dispose(); consumer.Dispose(); foreach (var queue in queues) { Output.WriteLine($"{queue}:{expectedDict[queue]}-{dict[queue]}"); Assert.Equal(expectedDict[queue], dict[queue]); } }