/// <summary> /// 获取单条消息 /// </summary> /// <param name="basicGetMethod">回调函数</param> /// <param name="data">传过来,再传回去</param> public void BasicGet(ReceiveMessageDelegate <Tuple <bool, string, Dictionary <string, object> > > basicGetMethod, Dictionary <string, object> data = null) { try { using (var channel = this.GetConnection().CreateModel()) { BasicGetResult res = channel.BasicGet(RabbitConfig.QueueName, false); if (res != null) { //普通使用方式BasicGet //noAck = true,不需要回复,接收到消息后,queue上的消息就会清除 //noAck = false,需要回复,接收到消息后,queue上的消息不会被清除,直到调用channel.basicAck(deliveryTag, false); queue上的消息才会被清除 而且,在当前连接断开以前,其它客户端将不能收到此queue上的消息 IBasicProperties props = res.BasicProperties; bool t = res.Redelivered; t = true; string result = Encoding.UTF8.GetString(res.Body); channel.BasicAck(res.DeliveryTag, false); basicGetMethod(new Tuple <bool, string, Dictionary <string, object> >(true, result, data)); } else { basicGetMethod(new Tuple <bool, string, Dictionary <string, object> >(false, "未找到所需数据", data)); } } } catch (Exception ex) { // mqErrCnt++; LogCom.WriteExceptToFile(ex, "RabbitMQHelper.BasicGet"); } }
//若引用该组件的业务系统也使用AutoMapper,则重复Mapper.Initialize可能会导致错误,因此本组件暂不使用 public static void Configure() { try { Mapper.Initialize(cfg => { cfg.CreateMap <Log_OperateTrace, Log_OperateTraceR>(); RegisterAutoMapperProfiles(cfg); //cfg.AddProfile<Log_SystemMonitorProfile>(); }); Mapper.AssertConfigurationIsValid(); } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "AutoMapperConfig.Configure"); } }
public bool WriteData <T>(T model) { if (!bOK) { return(false); } try { Point pt = ConvertToInfluxDBRec <T>(model); var responseWrite = influxDbClient.Client.WriteAsync(pt, _dbName).Result; return(responseWrite.Success); } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "InfluxDBHelper.WriteData"); return(false); } }
/// <summary> /// 获取队列服务器的连接对象 /// </summary> /// <param name="ip">服务器ip</param> /// <param name="port">服务器的端口</param> /// <param name="userName">登录账户</param> /// <param name="password">登录密码</param> /// <param name="virtualHost">虚拟主机</param> /// <param name="heartbeat">心跳检测时间</param> /// <returns></returns> public static IConnection GetConnection(string ip, int port, string userName, string password, string virtualHost, ushort heartbeat) { try { ConnectionFactory cf = new ConnectionFactory() { // HostName = ip, Port = port, Endpoint = new AmqpTcpEndpoint(new Uri("amqp://" + ip + "/")), UserName = userName, Password = password, VirtualHost = virtualHost, RequestedHeartbeat = heartbeat, // AutomaticRecoveryEnabled = true }; return(cf.CreateConnection()); } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "RabbitMQHelper.GetConnection"); return(null); } }
public InfluxDBHelper(string dbName) { if (!bOK || bCannotConnect || influxDbClient == null) { bOK = false; return; } if (string.IsNullOrEmpty(dbName)) { dbName = "DefaultDB"; } _dbName = dbName; try { var response = influxDbClient.Database.CreateDatabaseAsync(dbName).Result;//若表存在,则跳过(不新建) if (response.StatusCode != System.Net.HttpStatusCode.OK) { bOK = false; } } catch (Exception ex) { bOK = false; LogCom.WriteExceptToFile(ex, "InfluxDBHelper.构造函数"); try { if (ex.InnerException.InnerException.Message == "无法连接到远程服务器") { bCannotConnect = true; } } catch { } } }
//队列消息生产 internal static ExeResEdm Send <T>(T model, MQType mqType) { lock (mqObj) { if (!bSendMsgUseMQ) { return(new ExeResEdm()); } string value = SerializerHelper.SerializeToString(model); var tt = RabbitSendDic[mqType]; try { return(tt.Send(value)); } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "RabbitMQHelper.Send<T>"); return(new ExeResEdm() { ErrCode = 1, ExBody = ex, Module = "RabbitMQHelper.Send<T>" }); } } }
/// <summary> /// 接受消息,使用委托进行处理,使用 EventingBasicConsumer 方法,3.6.12版本服务器接收出错 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="receiveMethod"></param> public void Receive2 <T>(ReceiveMessageDelegate <T> receiveMethod) { try { using (var channel = this.GetConnection().CreateModel()) { //是否使用路由 if (!string.IsNullOrWhiteSpace(this.RabbitConfig.Exchange)) { //声明路由 // channel.ExchangeDeclare(this.RabbitConfig.Exchange, this.RabbitConfig.ExchangeType.ToString(), this.RabbitConfig.DurableQueue); //声明队列且与交换机绑定 channel.QueueDeclare(this.RabbitConfig.QueueName, this.RabbitConfig.DurableQueue, false, false, null); // channel.QueueBind(this.RabbitConfig.QueueName, this.RabbitConfig.Exchange, this.RabbitConfig.RoutingKey); } else { channel.QueueDeclare(this.RabbitConfig.QueueName, this.RabbitConfig.DurableQueue, false, false, null); } //输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息 channel.BasicQos(0, 1, false); ///告诉RabbitMQ同一时间给一个消息给消费者 //在队列上定义一个消费者 var consumer = new EventingBasicConsumer(channel); //消费队列,并设置应答模式为程序主动应答,oAck设置false,告诉broker,发送消息之后,消息暂时不要删除,等消费者处理完成再说 channel.BasicConsume(this.RabbitConfig.QueueName, false, consumer); consumer.Received += (model, ea) => { ProcessingResultsEnum processingResult = ProcessingResultsEnum.Retry; ulong deliveryTag = 0; try { //获取信息 deliveryTag = ea.DeliveryTag; byte[] bytes = ea.Body; string str = Encoding.UTF8.GetString(bytes); T v = SerializerHelper.DeserializeToObject <T>(str); receiveMethod(v); processingResult = ProcessingResultsEnum.Accept; //处理成功 // channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); //处理完成,告诉Broker可以服务端可以删除消息,分配新的消息过来 } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "RabbitMQHelper.Receive"); processingResult = ProcessingResultsEnum.Reject; //系统无法处理的错误 } finally { System.Threading.Thread.Sleep(100);//暂停0.1秒,防止CPU爆满的问题 switch (processingResult) { case ProcessingResultsEnum.Accept: //回复确认处理成功 channel.BasicAck(deliveryTag, false); break; case ProcessingResultsEnum.Retry: //发生错误了,但是还可以重新提交给队列重新分配 channel.BasicNack(deliveryTag, false, true); break; case ProcessingResultsEnum.Reject: //发生严重错误,无法继续进行,这种情况应该写日志或者是发送消息通知管理员 channel.BasicNack(deliveryTag, false, false); //写日志 break; } } }; } } catch (Exception ex) { LogCom.WriteExceptToFile(ex, "RabbitMQHelper.Receive"); } }
/// <summary> /// 接受消息,使用委托进行处理,使用QueueingBasicConsumer方法(已过时) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="receiveMethod"></param> public ExeResEdm Receive <T>(ReceiveMessageDelegate <T> receiveMethod) { ExeResEdm exeResEdm = new ExeResEdm() { }; try { using (var channel = this.GetConnection().CreateModel()) { //是否使用路由 if (!string.IsNullOrWhiteSpace(this.RabbitConfig.Exchange)) { //声明路由 // channel.ExchangeDeclare(this.RabbitConfig.Exchange, this.RabbitConfig.ExchangeType.ToString(), this.RabbitConfig.DurableQueue); //声明队列且与交换机绑定 channel.QueueDeclare(this.RabbitConfig.QueueName, this.RabbitConfig.DurableQueue, false, false, null); channel.QueueBind(this.RabbitConfig.QueueName, this.RabbitConfig.Exchange, this.RabbitConfig.RoutingKey); } else { channel.QueueDeclare(this.RabbitConfig.QueueName, this.RabbitConfig.DurableQueue, false, false, null); } //输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息 channel.BasicQos(0, 1, false); ///告诉RabbitMQ同一时间给一个消息给消费者 //在队列上定义一个消费者 var consumer = new QueueingBasicConsumer(channel); //消费队列,并设置应答模式为程序主动应答 channel.BasicConsume(this.RabbitConfig.QueueName, false, consumer); while (true) { //阻塞函数,获取队列中的消息 ProcessingResultsEnum processingResult = ProcessingResultsEnum.Retry; ulong deliveryTag = 0; try { //获取信息 var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); deliveryTag = ea.DeliveryTag; byte[] bytes = ea.Body; string str = Encoding.UTF8.GetString(bytes); T v = SerializerHelper.DeserializeToObject <T>(str); receiveMethod(v); processingResult = ProcessingResultsEnum.Accept; //处理成功 } catch //(Exception ex) { processingResult = ProcessingResultsEnum.Reject; //系统无法处理的错误 } finally { System.Threading.Thread.Sleep(100);//暂停0.1秒,防止CPU爆满的问题 switch (processingResult) { case ProcessingResultsEnum.Accept: //回复确认处理成功 channel.BasicAck(deliveryTag, false); break; case ProcessingResultsEnum.Retry: //发生错误了,但是还可以重新提交给队列重新分配 channel.BasicNack(deliveryTag, false, true); break; case ProcessingResultsEnum.Reject: //发生严重错误,无法继续进行,这种情况应该写日志或者是发送消息通知管理员 channel.BasicNack(deliveryTag, false, false); //写日志 break; } } } } } catch (Exception ex) { exeResEdm.ErrCode = 1; exeResEdm.ExBody = ex; exeResEdm.Module = "RabbitMQHelper.Receive方法"; LogCom.WriteExceptToFile(ex, "RabbitMQHelper.Receive"); } return(exeResEdm); }