Example #1
0
        private void materialFlatButton1_Click(object sender, EventArgs e)
        {
            var model = new VirtualHost();
            //listVirtualHostForm.Add(newItem);var dialog = new VirtualHostManager.Forms.VirtualHostDetail();
            var dialog = new VirtualHostManager.Forms.VirtualHostDetail();

            dialog.formType     = VirtualHostDetailType.Edit;
            dialog.Url          = "";
            dialog.Directory    = "";
            dialog.CreateAt     = "";
            dialog.Description  = "";
            dialog.Context      = dataStorageService.VirualHostTemplateRead(AppConst.VirtualHostTemplate);
            dialog.Status       = true;
            dialog.saveCallback = () =>
            {
                model.Url         = dialog.Url;
                model.Directory   = dialog.Directory;
                model.CreateAt    = DateTime.Now.ToString();
                model.UpdateAt    = DateTime.Now.ToString();
                model.Description = dialog.Description;
                model.Context     = dialog.Context;
                model.Status      = dialog.Status;
                model.Author      = dialog.Author;
                context.data.Add(model);
                //Rebind the Datagridview with the data.
                RebindGridForPageChange();
                setItems();
            };
            using (Panel p = this.blurPanel())
            {
                dialog.ShowDialog();
            }
        }
        public async Task <IActionResult> PutVirtualHost([FromRoute] int id, [FromBody] VirtualHost virtualHost)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != virtualHost.Id)
            {
                return(BadRequest());
            }

            _virtualHostRepository.Edit(virtualHost);

            try
            {
                await _virtualHostRepository.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VirtualHostExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public static RouteConfiguration CreateRoute(string routeName, string clusterName)
        {
            var virtualHost = new VirtualHost
            {
                Name = "all",
            };

            virtualHost.Domains.Add("*");
            virtualHost.Routes.Add(new Route
            {
                Match = new RouteMatch
                {
                    Prefix = "/"
                },
                Route_ = new RouteAction
                {
                    Cluster = clusterName
                },
            });

            var routeConfiguration = new RouteConfiguration {
                Name = routeName
            };

            routeConfiguration.VirtualHosts.Add(virtualHost);
            return(routeConfiguration);
        }
Example #4
0
 /// <summary>
 /// 指定虚拟机,发送特定routerKey的消息
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="exChangeName"></param>
 /// <param name="host"></param>
 /// <param name="queueName"></param>
 /// <returns></returns>
 public static bool PublishFanout(MQProtocol <M> msg, string exChangeName, VirtualHost host, string queueName = MQueueConst.DefaultGrantMQ)
 {
     msg.ExChange = exChangeName;
     using (FanoutPublisher <MQProtocol <M> > p = new FanoutPublisher <MQProtocol <M> >(msg, exChangeName, queueName, queueName, false, host))
     {
         return(p.Publish());
     }
 }
Example #5
0
        /// <summary>
        /// 指定虚拟机发送默认消息
        /// </summary>
        /// <param name="msg">msg</param>
        /// <param name="host">host</param>
        /// <returns>bool</returns>
        // public static bool Publish(MQProtocol<M> msg, VirtualHost host)
        // {
        //   return Publish(msg, RouterKeyConst.DefaultRouterKey, host);
        // }

        /// <summary>
        /// 注册一个默认配置的消费者,等待消息的到来
        /// </summary>
        /// <typeparam name="M">返回消息的实体类型</typeparam>
        /// <param name="autoDelete">是否自动删除,true为自动删除,false不会自动删除,需要业务自己删除</param>
        /// <param name="fn">
        /// 处理返回消息的回调,注意如果autoDelete指定为false说明调用方需要自己确定
        /// 消息什么时候删除,这里就需要fn返回是否删除,autoDelete指定为true时,fn这个返回值将不起作用
        /// </param>
        /// <returns></returns>
        // public static void ConsumeRegister(bool autoDelete,Func<MQProtocol<M>, Exception, bool> fn)
        // {
        //    // GrantDefaultConsumer<MQProtocol<M>> c = new GrantDefaultConsumer<MQProtocol<M>>(autoDelete);
        //    // c.OnGrantMsgReceive += (MQProtocol<M> m, Exception ex) =>
        //    // {
        //    //   return fn(m, ex);
        //    // };
        //    // consumers.Add(c);
        //    // c.Register();
        //    ConsumeRegister(RouterKeyConst.DefaultRouterKey, autoDelete, fn);
        // }

        /// <summary>
        /// 指定虚拟机,发送特定routerKey的消息
        /// </summary>
        /// <param name="msg">msg</param>
        /// <param name="routerKey">routerKey</param>
        /// <param name="host">host</param>
        /// <returns>bool</returns>
        public static bool Publish(MQProtocol <M> msg, string routerKey, VirtualHost host)
        {
            msg.ExChange  = ExchangeConst.DefaultExchange;
            msg.RouterKey = routerKey;
            using (GrantPublisher <MQProtocol <M> > p = new GrantPublisher <MQProtocol <M> >(msg, ExchangeConst.DefaultExchange, routerKey, MQueueConst.DefaultGrantMQ, false, host))
            {
                // consumers.Add(p);
                return(p.Publish());
            }
        }
Example #6
0
        public override int GetHashCode()
        {
            int hashCode = (HostName != null ? HostName.GetHashCode() : 0);

            hashCode = (hashCode * 397) ^ (VirtualHost != null ? VirtualHost.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ Port;
            hashCode = (hashCode * 397) ^ (Username != null ? Username.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (Password != null ? Password.GetHashCode() : 0);
            return(hashCode);
        }
Example #7
0
        /// <summary>
        /// 注册一个指定了Host的特定routerKey的消费者
        /// </summary>
        /// <param name="routerKey">注册接受特定的routerKey的消息</param>
        /// <param name="queueName">将特定的routerKey的消息接受到自己的queueName中</param>
        /// <param name="host">特定的host服务器</param>
        /// <param name="autoDelete">是否自动删除autoDelete,一般不要在注册的时候设置为true,在处理完消息的回调中删除消息</param>
        /// <param name="fn">回调fn</param>
        public static void ConsumeRegister(string routerKey, string queueName, VirtualHost host, bool autoDelete, Func <MQProtocol <M>, Exception, bool> fn)
        {
            GrantConsumer <MQProtocol <M> > c = new GrantConsumer <MQProtocol <M> >(ExchangeConst.DefaultExchange, routerKey, queueName, autoDelete, host);

            c.OnGrantMsgReceive += (MQProtocol <M> m, Exception ex) =>
            {
                return(fn(m, ex));
            };
            consumers.Add(c);
            c.Register();
        }
Example #8
0
        // Tries to convert text into a virtual host object.
        public VirtualHost ConvertToVirtualHost(string input)
        {
            // Use regex to get try and get essential details. Massive use of Elvis opperator here.
            var active     = Regex.Match(input, RegexHost)?.Groups[1]?.Value?.Trim() != "##";
            var host       = Regex.Match(input, RegexHost)?.Groups[2]?.Value?.Trim().Split(':'); // Split into name and port.
            var serverName = Regex.Match(input, RegexServerName)?.Groups[2]?.Value?.Trim();
            var docRoot    = Regex.Match(input, RegexDocumentRoot)?.Groups[2]?.Value?.Trim().Replace("\"", string.Empty);

            // Check we have required fields.
            if (string.IsNullOrEmpty(host[0]) || string.IsNullOrEmpty(serverName) || string.IsNullOrEmpty(docRoot))
            {
                throw new ArgumentNullException("Required parameters not parsed");
            }

            var hostName = host[0];
            // Create new VirtualHost now we have minimum fields.
            var vHost = new VirtualHost(hostName, serverName, docRoot, active);

            // Add any port we may have removed.
            int port;

            if (host.Length == 2 && int.TryParse(host[1], out port))
            {
                vHost.Port = port;
            }

            // Check for extra fields and add them if present.
            var serAdmin = Regex.Match(input, RegexServerAdmin)?.Groups[2]?.Value?.Trim();

            if (!string.IsNullOrEmpty(serAdmin))
            {
                vHost.ServerAdmin = serAdmin;
            }
            var serAlias = Regex.Match(input, RegexServerAlias)?.Groups[2]?.Value?.Trim();

            if (!string.IsNullOrEmpty(serAlias))
            {
                vHost.ServerAlias = serAlias;
            }
            var eLog = Regex.Match(input, RegexErrorLog)?.Groups[2]?.Value?.Trim();

            if (!string.IsNullOrEmpty(eLog))
            {
                vHost.ErrorLog = eLog;
            }
            var cLog = Regex.Match(input, RegexCustomLog)?.Groups[2]?.Value?.Trim();

            if (!string.IsNullOrEmpty(cLog))
            {
                vHost.CustomLog = cLog;
            }

            return(vHost);
        }
Example #9
0
        /// <summary>
        /// Responds to the save command from the current (sub) view model.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _currentViewModel_OnSaved(object sender, System.EventArgs e)
        {
            if (CurrentViewModel is VirtualHostVM)
            {
                var vHost = ((VirtualHostVM)CurrentViewModel).SelectedVirtualHost;
                if (vHost == null)
                {
                    return;
                }

                var old = VirtualHosts.FirstOrDefault(p => p.Id == vHost.Id);

                if (old == null)
                {
                    VirtualHosts.Add(vHost);
                }
                else
                {
                    var idx = VirtualHosts.IndexOf(old);
                    VirtualHosts.Remove(old);
                    VirtualHosts.Insert(idx, vHost);
                }

                // This bypasses the INotify event.
                // Currently there doesn't seem much point firing the event, but this may change later.
                _selectedVirtualHost = vHost;
            }
            else if (CurrentViewModel is HostFileEntryVM)
            {
                var host = ((HostFileEntryVM)CurrentViewModel).CurrentHostFileEntry;
                if (host == null)
                {
                    return;
                }

                var old = HostFileEntries.FirstOrDefault(p => p.Id == host.Id);

                if (old == null)
                {
                    HostFileEntries.Add(host);
                }
                else
                {
                    var idx = HostFileEntries.IndexOf(old);
                    HostFileEntries.Remove(old);
                    HostFileEntries.Insert(idx, host);
                }

                // This bypasses the INotify event.
                // Currently there doesn't seem much point firing the event, but this may change later.
                _selectedHostFileEntry = host;
            }
        }
Example #10
0
        public override bool Equals(object obj)
        {
            var otherEndpoint = obj as Endpoint;

            if (otherEndpoint == null)
            {
                return(false);
            }

            return(HostName.Equals(otherEndpoint.HostName) && VirtualHost.Equals(otherEndpoint.VirtualHost) &&
                   UserName.Equals(otherEndpoint.UserName) && Password.Equals(otherEndpoint.Password));
        }
        public async Task <IActionResult> PostBlacklistedResource([FromBody] VirtualHost virtualHost)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _virtualHostRepository.AddAsync(virtualHost);

            await _virtualHostRepository.SaveChangesAsync();

            return(CreatedAtAction("GetVirtualHost", new { id = virtualHost.Id }, virtualHost));
        }
        private Uri FormatHostAddress()
        {
            var builder = new UriBuilder
            {
                Scheme = "rabbitmq",
                Host   = Host,
                Port   = Port == 5672 ? 0 : Port,
                Path   = string.IsNullOrWhiteSpace(VirtualHost) || VirtualHost == "/"
                    ? "/"
                    : $"/{VirtualHost.Trim('/')}"
            };

            return(builder.Uri);
        }
        public static RouteConfiguration ToRouteConfiguration(this IEnumerable <Route> routes, string name)
        {
            var envoyEgressRoute = new RouteConfiguration()
            {
                Name = name
            };
            var vHost = new VirtualHost {
                Name = $"{name}Services"
            };

            vHost.Domains.Add("*");
            vHost.Routes.AddRange(routes);
            envoyEgressRoute.VirtualHosts.Add(vHost);
            return(envoyEgressRoute);
        }
Example #14
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = (Broker != null ? Broker.GetHashCode() : 0);
         result = (result * 397) ^ (VirtualHost != null ? VirtualHost.GetHashCode() : 0);
         result = (result * 397) ^ (Username != null ? Username.GetHashCode() : 0);
         result = (result * 397) ^ (Password != null ? Password.GetHashCode() : 0);
         result = (result * 397) ^ (Exchange != null ? Exchange.GetHashCode() : 0);
         result = (result * 397) ^ (QueueName != null ? QueueName.GetHashCode() : 0);
         result = (result * 397) ^ (RoutingKeys != null ? RoutingKeys.GetHashCode() : 0);
         result = (result * 397) ^ RouteByType.GetHashCode();
         return(result);
     }
 }
Example #15
0
        public override bool Equals(object obj)
        {
            var otherQueue = obj as Queue;

            if (otherQueue == null)
            {
                return(false);
            }

            return(Username.Equals(otherQueue.Username) &&
                   Password.Equals(otherQueue.Password) &&
                   VirtualHost.Equals(otherQueue.VirtualHost, StringComparison.OrdinalIgnoreCase) &&
                   Host.Equals(otherQueue.Host, StringComparison.OrdinalIgnoreCase) &&
                   Port.Equals(otherQueue.Port));
        }
Example #16
0
        private void OnExecute(IConsole console)
        {
            var dirPath          = Environment.CurrentDirectory;
            var dirName          = Path.GetFileName(dirPath);
            var defaultExtension = Config.Get("App", "VhostExtension");
            var givenDomain      = dirName.ToLower() + defaultExtension;

            if (Domain != null)
            {
                givenDomain = Domain;
            }

            // TODO: fix domain tld validator
            if (!Utilities.IsValidDomainName(givenDomain))
            {
                ColorizeConsole.PrintlnError($"\n> Please specify a valid domain name!\n");
                return;
            }

            var vhostFile = VirtualHost.ApacheVhostDir + @"\" + givenDomain + ".conf";

            if (File.Exists(vhostFile))
            {
                ColorizeConsole.PrintlnError($"\n> VirtualHost already exists!\n");
                return;
            }

            ColorizeConsole.PrintlnInfo($"\n> Creating virtualhost ...");
            VirtualHost.CreateCert(givenDomain);
            VirtualHost.CreateVhost(givenDomain, dirPath.Replace("\\", "/"));
            if (DnsHostfile.IsNotExists(givenDomain))
            {
                DnsHostfile.AddRecord(givenDomain);
            }

            // TODO: services restart command still not working
            // ColorizeConsole.PrintlnInfo($"\n> Reloading services ...");
            // Services.Reload(References.ServiceNameHttp);
            // Task.Delay(TimeSpan.FromSeconds(5));

            ColorizeConsole.PrintlnSuccess($"\n> Virtualhost has been created, please restart Varlet services in VarletUi!");
            ColorizeConsole.PrintlnWarning($"> Your site will be available at: http://{givenDomain} and https://{givenDomain}\n");
        }
        public IEnumerable <string> GetAllUnidentifiedResourceRequestsSince(VirtualHost virtualHost, DateTime startDateTime, string path)
        {
            var logFilePaths = new List <string>();

            foreach (var accessLog in virtualHost.AccessLogFiles)
            {
                logFilePaths.AddRange(_accessLogFinder.GetLogFilesCreatedOnOrAfter(startDateTime, path, accessLog.AccessLogFilenameConfig));
            }

            var unidentifiedResourceRequests = new List <string>();

            foreach (var file in logFilePaths)
            {
                _accessLogAnalyser.GetAllUnidentifiedResourceRequestsInLogFile(file);
            }


            return(unidentifiedResourceRequests);
        }
Example #18
0
 /// <summary>
 /// 接受广播消息的消费者
 /// </summary>
 /// <param name="exchange"></param>
 /// <param name="queueName"></param>
 /// <param name="autoDelete"></param>
 /// <param name="host"></param>
 /// <param name="_objCtx"></param>
 public FanoutConsumer(string exchange, string queueName, bool autoDelete, VirtualHost host, object _objCtx = null)
     : base(new MQueue()
 {
     AutoDeclare = false,
     AutoDelete  = autoDelete,
     Durable     = true,
     Exchange    = new Exchange()
     {
         AutoDeclare  = false,
         AutoDelete   = false,
         Durable      = true,
         ExchangeType = ExchangeType.Fanout,
         ExchangeName = exchange,
     },
     Exclusive = false,
     QueueName = queueName,
     RouteKey  = "",
     Host      = host,
 }, _objCtx)
 {
 }
Example #19
0
        /// <summary>
        /// Sets associated objects when required.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _objectViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            object obj = null;

            switch (e.PropertyName)
            {
            case "CurrentHostFileEntry":
                // Set the backing value so we skip the actions that occur when assigning to the public property.
                _selectedVirtualHost = VirtualHosts.FirstOrDefault(
                    p => p.ServerName == SelectedHostFileEntry.Url ||
                    p.ServerAlias == SelectedHostFileEntry.Url);

                // Assign found value to obj, even if null as this will tell the viewmodel to clear the property.
                obj = _selectedVirtualHost;

                // Now we need to raise the property changed event on the changed property to allow UI to react.
                OnPropertyChanged("SelectedVirtualHost");
                break;

            case "SelectedVirtualHost":
                _selectedHostFileEntry = HostFileEntries.FirstOrDefault(
                    p => p.Url == SelectedVirtualHost.ServerName ||
                    p.Url == SelectedVirtualHost.ServerAlias);

                obj = _selectedHostFileEntry;

                OnPropertyChanged("SelectedHostFileEntry");
                break;

            default:
                // If not a property we want to act on we should return to prevent setting unwanted values.
                return;
            }
            CurrentViewModel.SetAssociatedObject(obj);
        }
Example #20
0
        public static void Initlize(Config.RabbitMQ el)
        {
            try
            {
                readerWriterLock.AcquireWriterLock(80);
                if (el != null && el.Host != null && el.Host.Count > 0)
                {
                    for (int i = 0; i < el.Host.Count; i++)
                    {
                        int         port = 0;
                        VirtualHost h    = new VirtualHost();
                        h.HostName      = el.Host[i].Name;
                        h.Host          = el.Host[i].Ip;
                        h.Port          = el.Host[i].Port;
                        h.Username      = el.Host[i].UserName;
                        h.Password      = el.Host[i].PassWord;
                        h.NoAckMsgCount = el.Host[i].NoAckMsgCount;

                        // 如果配置了同名,跳过
                        if (!_host.ContainsKey(h.HostName.ToLower()))
                        {
                            _host.Add(h.HostName.ToLower(), h);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "初始化RabbbitMQ异常");
            }
            finally
            {
                if (readerWriterLock.IsWriterLockHeld)
                {
                    readerWriterLock.ReleaseWriterLock();
                }
            }
        }
Example #21
0
        private static void AutoGenerateVhost()
        {
            // Remove old vhost
            var files = (new DirectoryInfo(VirtualHost.ApacheVhostDir)).GetFiles("auto.*.conf");

            foreach (var file in files)
            {
                var domain = file.Name.Replace("auto.", "").Replace(".conf", "");
                if (!DnsHostfile.IsNotExists(domain))
                {
                    DnsHostfile.DeleteRecord(domain);
                }
                File.Delete(file.FullName);
            }

            // Generate auto virtualhost
            var wwwDir = Config.Get("App", "DocumentRoot");

            if (!Directory.Exists(wwwDir))
            {
                return;
            }
            foreach (var dir in Directory.GetDirectories(wwwDir))
            {
                var dirName = Path.GetFileName(dir);
                var dirPath = wwwDir + @"\" + dirName;
                var domain  = dirName + Config.Get("App", "VhostExtension");
                VirtualHost.CreateCert(domain);
                VirtualHost.CreateVhost(domain, dirPath, true);
                if (DnsHostfile.IsNotExists(domain))
                {
                    DnsHostfile.AddRecord(domain);
                }
            }
            VirtualHost.SetDefaultVhost();
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
        }
Example #22
0
 /// <summary>
 /// 添加发布者广播消息
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="exchangeName"></param>
 /// <param name="routeKey"></param>
 /// <param name="queueName"></param>
 /// <param name="autoDelete"></param>
 /// <param name="host"></param>
 public FanoutPublisher(TM msg, string exchangeName, string routeKey, string queueName, bool autoDelete, VirtualHost host)
     : base(msg, exchangeName, routeKey, queueName, autoDelete, host, ExchangeType.Fanout)
 {
 }
Example #23
0
 public PullConsumer(string exchange, string routeKey, string queueName, bool autoDelete, VirtualHost host)
     : this(new MQueue()
 {
     AutoDeclare = false,
     AutoDelete = autoDelete,
     Durable = true,
     Exchange = new Exchange()
     {
         AutoDeclare = false,
         AutoDelete = false,
         Durable = true,
         ExchangeType = ExchangeType.Direct,
         ExchangeName = exchange,
     },
     Exclusive = false,
     QueueName = queueName,
     RouteKey = routeKey,
     Host = host,
 })
 {
 }
Example #24
0
 public Request(HttpRequest requestObject, VirtualHost virtualHost)
 {
     Object      = requestObject;
     VirtualHost = virtualHost;
 }
Example #25
0
        /// <summary>
        /// 注册一个指定了Host的特定routerKey的拉消费者
        /// </summary>
        /// <param name="routerKey">注册接受特定的routerKey的消息</param>
        /// <param name="queueName">将特定的routerKey的消息接受到自己的queueName中</param>
        /// <param name="host">特定的host服务器</param>
        /// <param name="autoDelete">是否自动删除autoDelete,一般不要在注册的时候设置为true,在处理完消息的回调中删除消息</param>
        public static GrantPullConsumer <MQProtocol <M> > PullConsumeRegister(string routerKey, string queueName, VirtualHost host, bool autoDelete)
        {
            GrantPullConsumer <MQProtocol <M> > c = new GrantPullConsumer <MQProtocol <M> >(ExchangeConst.DefaultExchange, routerKey, queueName, autoDelete, host);

            consumers.Add(c);
            c.Register();
            return(c);
        }
Example #26
0
 protected bool Equals(VirtualHost other)
 {
     return string.Equals(Name, other.Name);
 }
Example #27
0
 protected bool Equals(VirtualHost other)
 {
     return(string.Equals(Name, other.Name));
 }
Example #28
0
 /// <summary>
 /// 添加发布者消息
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="exchangeName"></param>
 /// <param name="routeKey"></param>
 /// <param name="queueName"></param>
 /// <param name="autoDelete"></param>
 /// <param name="host"></param>
 /// <param name="exchangeType"></param>
 public DefaultPublisher(M msg, string exchangeName, string routeKey, string queueName, bool autoDelete, VirtualHost host, string exchangeType = ExchangeType.Direct)
     : base(msg, exchangeName, routeKey, queueName, autoDelete, host)
 {
 }
Example #29
0
        internal async Task <QueueConnection> GetConnection(MessageContext context)
        {
            string user = null;
            string pass = null;
            string host = null;
            string virt = null;
            int    port = 0;

            string dsUri = null;

            if (URI != null)
            {
                dsUri = await URI.SelectStringAsync(context);
            }
            else
            {
                var userTask   = User?.SelectStringAsync(context);
                var passTask   = Password?.SelectStringAsync(context);
                var hostTask   = Host?.SelectStringAsync(context);
                var portTask   = Port?.SelectStringAsync(context);
                var virtTask   = VirtualHost?.SelectStringAsync(context);
                var paramTasks = new Task <string>[] { userTask, passTask, hostTask, portTask, virtTask };
                Task.WaitAll(paramTasks.Where(x => x != null).ToArray());

                user = userTask?.Result;
                pass = passTask?.Result;
                host = hostTask?.Result;
                virt = virtTask?.Result;
                if (portTask != null)
                {
                    int.TryParse(portTask.Result, out port);
                }

                dsUri = String.Format("amqp://{0}:{1}@{2}:{3}/{4}",
                                      user,
                                      pass,
                                      host,
                                      port,
                                      virt);
            }

            if (Connections.ContainsKey(dsUri))
            {
                return(Connections[dsUri]);
            }
            else
            {
                ConnectionFactory factory = new ConnectionFactory();

                if (URI != null)
                {
                    factory.Uri = new Uri(dsUri);
                }
                else
                {
                    // We've already made a Uri for the sake of having a dictionary key, but we'll pass these into
                    // the factory separatey in case Rabbit's code does any optimisations, so revisit this after
                    // some benchmarking.
                    if (user != null)
                    {
                        factory.UserName = user;
                    }
                    if (pass != null)
                    {
                        factory.Password = pass;
                    }
                    if (host != null)
                    {
                        factory.HostName = host;
                    }
                    if (virt != null)
                    {
                        factory.VirtualHost = virt;
                    }
                    if (port > 0)
                    {
                        factory.Port = port;
                    }
                }

                QueueConnection qc = null;
                try
                {
                    qc = new QueueConnection(factory.CreateConnection());
                }
                catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException buex)
                {
                    logger.Error(buex, "Queue Broker (RabbitMQ service) is unreachable. Is there one running at {0}? ({1})", factory.Endpoint.ToString(), buex.Message);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "{0} thrown when attempting to get RabbitMQ connection: {1}", ex.GetType().Name, ex.Message);
                    throw;
                }

                Connections.TryAdd(dsUri, qc);
                return(qc);
            }
        }
Example #30
0
        /// <summary>
        /// 注册一个接受广播消费者
        /// </summary>
        /// <param name="exChangeName">交换机名称</param>
        /// <param name="queueName">队列名称</param>
        /// <param name="host"></param>
        /// <param name="autoDelete"></param>
        /// <param name="fn"></param>
        /// <param name="_objCtx"></param>
        public static void FanoutConsumeRegister(string exChangeName, string queueName, VirtualHost host, bool autoDelete, Func <MQProtocol <M>, Exception, object, bool> fn, object _objCtx)
        {
            FanoutConsumer <MQProtocol <M> > c = new FanoutConsumer <MQProtocol <M> >(exChangeName, queueName, autoDelete, host, _objCtx);

            c.OnGrantMsgReceive += (MQProtocol <M> m, Exception ex, object objCtx) =>
            {
                return(fn(m, ex, objCtx));
            };
            consumers.Add(c);
            c.Register();
        }