using DSWeb.Common.DB; using log4net; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSWeb.EventBus { public static class MqProcActionLog { private const string ExchangeName = "djy.action"; private const string QueueName = "djy.action"; private static string FeedbackMqUri = ConfigurationManager.AppSettings["ActionLogMQUri"]; private static IConnection mqConn; private static ILog logger = LogManager.GetLogger("MqProcActionLog"); public static void DoProcess() { logger.Debug($"动作记录开始执行"); ConnectionFactory factory = new ConnectionFactory(); factory.Uri = new Uri(FeedbackMqUri); mqConn = factory.CreateConnection(); IModel model = mqConn.CreateModel(); model.ExchangeDeclare(ExchangeName, ExchangeType.Direct); model.QueueDeclare(QueueName, false, false, false, null); var consumer = new EventingBasicConsumer(model); consumer.Received += (ch, ea) => { var body = ea.Body; var strBody = Encoding.UTF8.GetString(body.ToArray()); logger.Debug($"动作记录数据:{strBody}"); try { //保存数据 var objRec = JsonConvert.DeserializeObject(strBody); DjyActionDataContext djyActionData = new DjyActionDataContext(); objRec.GID = Guid.NewGuid().ToString(); djyActionData.DjyActionLog.Add(objRec); djyActionData.SaveChanges(); } catch (Exception ex) { logger.Error($"处理动作记录数据时出错:"); logger.Error(ex.Message); logger.Error(ex.StackTrace); } }; model.BasicConsume(QueueName, true, consumer); } public static void StopProcess() { if (mqConn != null && mqConn.IsOpen) { mqConn.Close(); mqConn = null; } } } }