Пример #1
0
        private void Resolver_Started(string obj)
        {
            Trace.TraceInformation("Resolver started");

            //Self resolving timeout, exiting ...
            int timeout  = Config.Starter.registerselftimeout ?? 10000;
            var register = Resolver.RegisterSelf();

            if (Task.WhenAny(register, Task.Delay(timeout)).Result != register)
            {
                throw new CoreException("Resolver self register timeout expired!");
            }

            var links = register.Result;

            Trace.TraceInformation("Self links resolved");

            int queueInc = 2;

            if (links != null)
            {
                foreach (var link in links)
                {
                    var exchangeName = ExchangeTypes.GetExchangeName(link.name, link.type, null);

                    Trace.TraceInformation($"Bind {exchangeName} start..");

                    ConsumerParam options = new ConsumerParam();
                    options.QueueParam = new ChannelQueueParam()
                    {
                        AutoDelete = Config.MQ.autodelete ?? false,
                    };
                    if (Config.MQ.queue.ttl.HasValue)
                    {
                        options.QueueParam.SetExpiresMs(Config.MQ.queue.ttl.Value);
                    }
                    switch (link.type)
                    {
                    case LinkTypes.LINK_EXCHANGE:
                    {
                        ExchangeConnectionString = exchangeName;
                        options.QueueParam.Name  = $"{exchangeName}.{AppId}";
                        options.ExchangeParam    = new ChannelExchangeParam()
                        {
                            Name       = exchangeName,
                            AutoDelete = Config.MQ.autodelete ?? false
                        };
                        if (Config.MQ.exchange.ttl.HasValue)
                        {
                            options.ExchangeParam.SetExpiresMs(Config.MQ.exchange.ttl.Value);
                        }
                    }
                    break;

                    case LinkTypes.LINK_QUEUE:
                    {
                        QueueConnectionString   = exchangeName;
                        options.QueueParam.Name = exchangeName;
                    }
                    break;

                    default: { Trace.TraceWarning($"Unknow link type: [{link.type}]"); continue; }
                    }

                    //Максимальный пул одновременных сообщений контролируется параметром ru:spinosa:mq:prefetch
                    //т.е. максимальным числом полученных сообщений оставленных без ответа
                    Connection.Listen(options, (ea) =>
                    {
                        Task.Run(() => this.HandleMessage(ea))
                        .ContinueWith(res => { this.HandleMessageErrors?.Invoke(ea, res.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
                    });

                    Trace.TraceInformation($"Bind {exchangeName} successed");
                    queueInc--;
                }
            }

            if (queueInc == 0)
            {
                this.running = true;
                //запускаем обновление кэша только если удалось получить собственные ссылки т.к. это подтверждает, что оператор запущен и имеет смысл к нему обращаться
                //

                if (Config.Starter.pingperiod_ms.HasValue)
                {
                    Trace.TraceInformation($"RunRefreshCache started {Config.Starter.pingperiod_ms.Value}ms");
                    Resolver.RunRefreshCache();
                }
                Started?.Invoke(AppId);
            }
            else
            {
                throw new CoreException("Self links bind error:  queueInc!=0 ");
            }
        }
Пример #2
0
        private Task <DataArgs <ViaElement> > Push(ViaElement via, bool requestResolve, string link, string service, string exchangeName, string routingKey, string exchangeType, string queryData, IBasicProperties properties)
        {
            DataArgs <ViaElement> messageEventArgs = new DataArgs <ViaElement>();

            if (requestResolve)
            {
                //Для начала надо узнать в какие очереди посылать запросы
                return(this.Dispatcher.Resolve(service, link)
                       .ContinueWith(resolver_link =>
                {
                    //try
                    //{
                    if (resolver_link.Exception != null)
                    {
                        messageEventArgs.SetException(resolver_link.Exception);
                    }
                    var link_str = resolver_link.Result;
                    var exchange = ExchangeTypes.GetExchangeName(link_str, null, exchangeType);
                    bool isFanout = ExchangeType.Fanout.Equals(exchangeType, StringComparison.CurrentCultureIgnoreCase);

                    var rk = isFanout ? exchange : routingKey;

                    var options = new ProducerParam()
                    {
                        RoutingKey = rk
                    };

                    if (!isFanout)
                    {
                        options.ExchangeParam = new ChannelExchangeParam()
                        {
                            Name = exchange,
                            Type = exchangeType ?? ExchangeTypes.EXCHANGETYPE_FANOUT
                        };
                    }

                    var data = Encoding.UTF8.GetBytes(queryData);
                    //посылаем сообщение
                    Dispatcher.Connection.Publish(options, data, properties);
                    messageEventArgs.result = true;
                    messageEventArgs.data = via;
                    //}
                    //catch (Exception ex)
                    //{
                    //    messageEventArgs.SetException(ex);
                    //}
                    return messageEventArgs;
                }));
            }
            else
            {
                return(Task.Run(() =>
                {
                    //try
                    //{
                    //для запросов, где очереди известны
                    var options = new ProducerParam()
                    {
                        RoutingKey = routingKey
                    };
                    if (!string.IsNullOrEmpty(exchangeName))
                    {
                        options.ExchangeParam = new ChannelExchangeParam()
                        {
                            Name = exchangeName,
                            Type = exchangeType ?? ExchangeTypes.EXCHANGETYPE_FANOUT
                        };
                    }

                    var data = Encoding.UTF8.GetBytes(queryData);
                    //посылаем сообщение
                    Dispatcher.Connection.Publish(options, data, properties);
                    //}
                    //catch (Exception ex)
                    //{
                    //    messageEventArgs.result = false;
                    //    messageEventArgs.SetException(ex);
                    //}
                    return messageEventArgs;
                }));
            }
        }