Beispiel #1
0
 public MQResult DirectPublish(mq_published published)
 {
     try
     {
         var     config  = generateMsgBody.GenerateQueueConfig(published) as RabbitPublishQueueConfig;
         Message message = JsonConvert.DeserializeObject <Message>(published.message);
         message.MsgSeq = 1;
         using (var channel = mqConnection.CreateModel())
         {
             channel.ConfirmSelect();
             channel.QueueDeclare(queue: config.QueueName, durable: true, exclusive: false, autoDelete: false, arguments: config.Args);
             channel.ExchangeDeclare(config.ExchangeName, ExchangeType.Direct);
             channel.QueueBind(config.QueueName, config.ExchangeName, config.RouteKey, null);
             var properties = channel.CreateBasicProperties();
             properties.Persistent = true;
             channel.BasicPublish(exchange: config.ExchangeName, routingKey: config.RouteKey, basicProperties: properties, body: message.ToBytes());
             if (!channel.WaitForConfirms(new TimeSpan(0, 0, 5)))
             {
                 return(new MQResult()
                 {
                     IsSucess = false, ExceptionMsg = "sent message failed"
                 });
             }
             Console.WriteLine($"[P] sent_message,queue={config.QueueName},msg={message.ToString()}");
             return(new MQResult()
             {
                 IsSucess = true, ChannelNumber = channel.ChannelNumber
             });
         }
     }
     catch (Exception ex)
     {
         //记log
         return(new MQResult()
         {
             IsSucess = false, ExceptionMsg = ex.Message
         });
     }
 }
Beispiel #2
0
        public async Task DoAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                MQTransOptions     options         = null;
                IMQTransRepository repository      = null;
                IMQOperate         mqOperate       = null;
                IMQGenerateMsgBody generateMsgBody = null;

                try
                {
                    using (var scope = Services.CreateScope())
                    {
                        IMQTransRedis redis        = null;
                        RedisOptions  redisOptions = null;
                        var           logid        = Guid.NewGuid().ToString();
                        _logger.LogInformation($"{logid}->发送消息JOB*BEGIN*{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                        repository      = scope.ServiceProvider.GetService <IMQTransRepository>();
                        mqOperate       = scope.ServiceProvider.GetService <IMQOperate>();
                        generateMsgBody = scope.ServiceProvider.GetService <IMQGenerateMsgBody>();
                        options         = scope.ServiceProvider.GetService <MQTransOptions>();
                        redis           = scope.ServiceProvider.GetService <IMQTransRedis>();
                        redisOptions    = scope.ServiceProvider.GetService <RedisOptions>();
                        var needSaveChange = false;
                        if (redis.LockTake(ConstValues.LockSendMsg + options.ServiceName, options.ServiceName, TimeSpan.FromSeconds(redisOptions.LockMsgSenconds)))
                        {
                            var needPublishMsgs = repository.GetNeedPublishMsgs(100, options.ServiceName);
                            _logger.LogInformation($"{logid}->发送消息JOB*COUNT*{needPublishMsgs.Count}*{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                            try
                            {
                                foreach (var msg in needPublishMsgs)
                                {
                                    var result = mqOperate.DirectPublish(generateMsgBody.GenerateQueueConfig(msg), JsonConvert.DeserializeObject <Message>(msg.message));
                                    if (result.IsSucess)
                                    {
                                        needSaveChange = true;
                                        repository.UpdateSuccessStatus(msg, options.ExpiresMinute);
                                    }
                                    else
                                    {
                                        //发送失败,不做处理,会自动重新发起
                                        _logger.LogError($"{logid}->发送消息JOB*未发送成功{JsonConvert.SerializeObject(result)}");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //未查到,不做处理,会自动重新发起
                                _logger.LogError($"{logid}->发送消息JOB*{ex.ToString()}");
                            }
                            finally
                            {
                                if (needSaveChange)
                                {
                                    if (!repository.SaveChange())
                                    {
                                        _logger.LogError($"{logid}->发送消息JOB*保存失败");
                                    }
                                }

                                var a = redis.LockRelease(ConstValues.LockSendMsg + options.ServiceName, options.ServiceName);
                                _logger.LogError($"{logid}->发送消息JOB*END*{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("发送消息JOB ERR:" + ex.ToString());
                }

                //3min
                Thread.Sleep(1000 * 60 * options.JobFrequencyMinute);
            }
        }