示例#1
0
        public PublishEventToRabbit(RabbitConnectionInfo connectionInfo, ISerializer serializer)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            if (string.IsNullOrEmpty(connectionInfo.ClientName))
            {
                throw new ArgumentException("Missing connectionInfo.ClientName");
            }

            this.serializer     = serializer ?? throw new ArgumentNullException(nameof(serializer));
            this.connectionInfo = connectionInfo;

            var factory = new ConnectionFactory
            {
                UserName = connectionInfo.UserName,
                Password = connectionInfo.Password,
                HostName = connectionInfo.Server,
                AutomaticRecoveryEnabled = true,
                VirtualHost = connectionInfo.VirtualHost ?? "/"
            };


            rabbitConnection = factory.CreateConnection(connectionInfo.ClientName);
            channel          = rabbitConnection.CreateModel();
        }
示例#2
0
        static void Main(string[] args)
        {
            var container = new SimpleFactory.Container();
            var con       = new RabbitConnectionInfo
            {
                ClientName   = "Listner.Demo",
                ExchangeName = "Simployer",
                Server       = "localhost",
                UserName     = "******",
                Password     = "******",
                VirtualHost  = "/"
            };

            var pub = new PublishEventToRabbit(con, new Serializer());

            container.Register <PublishEventToRabbit>(() => pub).Singleton(); //This is singleton to hold the connection stuff for rabbit. Must be disposed
            container.Register <CustomPublisher>().Transient();               //This is the wrapper to capture the context of the current call
            container.Register <ApplicationContext>();                        // this is the actual context.. Very simplefied :)

            for (var x = 0; x < 10; x++)
            {
                var sender = container.CreateInstance <CustomPublisher>();
                sender.Publish(new SomethingOccured {
                    Message = $"This is message number{x}"
                });
            }

            pub.Dispose();
        }
        /// <summary>
        /// 验证打开参数
        /// </summary>
        /// <param name="connectionInfo">连接信息</param>
        /// <returns>Rabbit连接信息</returns>
        private RabbitConnectionInfo ValidateOpenParams(ConnectionInfo connectionInfo)
        {
            ValidateUtil.ValidateNull(connectionInfo, "连接信息");
            RabbitConnectionInfo rabbitConnectionInfo = RabbitConnectionInfo.From(connectionInfo);

            if (connection != null && connection.IsOpen)
            {
                throw new Exception("已打开连接,不允许重复打开。如需打开不同连接请先关闭原有连接");
            }

            return(rabbitConnectionInfo);
        }
		public HttpBasedRabbitConsole(RabbitConnectionInfo connInfo)
		{
			_client	= new HttpClient()
			{
				BaseAddress	= new Uri(string.Format("http://{0}:15672/api/", connInfo.HostName))
			};

			_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
			_client.DefaultRequestHeaders.Authorization	= new AuthenticationHeaderValue("Basic",
				Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}",	connInfo.UserName, connInfo.Password))));
			_client.DefaultRequestHeaders.UserAgent.Add(new	ProductInfoHeaderValue("curl", "7.30.0"));
			_client.DefaultRequestHeaders.ConnectionClose =	true;
		}
        public HttpBasedRabbitConsole(RabbitConnectionInfo connInfo)
        {
            _client = new HttpClient()
            {
                BaseAddress = new Uri(string.Format("http://{0}:15672/api/", connInfo.HostName))
            };

            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                        Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", connInfo.UserName, connInfo.Password))));
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("curl", "7.30.0"));
            _client.DefaultRequestHeaders.ConnectionClose = true;
        }
 /// <summary>
 /// 根据Rabbit连接信息获取连接工厂
 /// </summary>
 /// <param name="rabbitConnectionInfo">Rabbit连接信息</param>
 /// <returns>连接工厂</returns>
 private ConnectionFactory GetConnectionFactory(RabbitConnectionInfo rabbitConnectionInfo)
 {
     return(new ConnectionFactory()
     {
         HostName = rabbitConnectionInfo.Host,
         VirtualHost = rabbitConnectionInfo.VirtualPath,
         Password = rabbitConnectionInfo.Password,
         UserName = rabbitConnectionInfo.User,
         Port = rabbitConnectionInfo.Port,
         AutomaticRecoveryEnabled = rabbitConnectionInfo.AutoRecovery,
         RequestedHeartbeat = rabbitConnectionInfo.Heartbeat
     });
 }
示例#7
0
        public RabbitMessageAdapter(RabbitConnectionInfo connectionInfo, ISerializer serializer, ILogger <RabbitMessageAdapter> logger)
        {
            this.logger            = logger;
            this.connectionFactory = new ConnectionFactory()
            {
                HostName    = connectionInfo.Server,
                UserName    = connectionInfo.UserName,
                Password    = connectionInfo.Password,
                VirtualHost = connectionInfo.VirtualHost ?? "/"
            };
            connectionFactory.AutomaticRecoveryEnabled = true;

            this.connectionInfo = connectionInfo;
            this.serializer     = serializer;
        }
        /// <summary>
        /// 根据Rabbit连接信息获取连接工厂
        /// </summary>
        /// <param name="rabbitConnectionInfo">Rabbit连接信息</param>
        /// <returns>连接工厂</returns>
        private ConnectionFactory GetConnectionFactory(RabbitConnectionInfo rabbitConnectionInfo)
        {
            var factory = new ConnectionFactory()
            {
                HostName    = rabbitConnectionInfo.Host,
                VirtualHost = rabbitConnectionInfo.VirtualPath,
                Password    = rabbitConnectionInfo.Password,
                UserName    = rabbitConnectionInfo.User,
                Port        = rabbitConnectionInfo.Port,
                AutomaticRecoveryEnabled = rabbitConnectionInfo.AutoRecovery,
                RequestedHeartbeat       = TimeSpan.FromSeconds(rabbitConnectionInfo.Heartbeat)
            };

            return(factory);
        }
示例#9
0
        static void Main(string[] args)
        {
            //Use any container..
            var container = new SimpleFactory.Container();

            container.Register <MyHandler>().Scoped();

            //Connectioninfo to the rabbit server.
            //The ClientName is important, as it is used in the infrastructure to indentify the host.
            RabbitConnectionInfo connectionInfo = new RabbitConnectionInfo {
                UserName = "******", Password = "******", Server = "localhost", ExchangeName = "Simployer", ClientName = "MyTestingApp"
            };

            //Create the RabbitAdapter. This is a spesific implementation for Rabbit.
            //IMessageAdapter messageAdapter = new RabbitMessageAdapter(
            //        connectionInfo,
            //        //The serializer that will be used by the adapter. This must implement the ISerializer from Itas.Infrastructure.
            //        new Serializer(),
            //        //This Func<BasicDeliveryEventArgs> gives you the chance to create a context value for your eventhandler.
            //        //Setting the ClientContext e.g
            //        (sp, eventArgs, data) => { }
            //    );

            //Then instanciate the MessageHandler.. Passing in the Adapter.
            //var server = new MessageHandlerEngine(
            //    messageAdapter,
            //    //This Func<Type,object> is used instead of taking a dependency on a Container.
            //    //Here you can create your scope to for your context
            //    () => new SimpleFactory.SimplefactoryProvider(container));
            ////Register a typed handler for the Engine.
            ////The engine will ask for an instance of  MessageHandle<MyEventClass> using the above Action<Type,object>.
            //server.AttachMessageHandler<SomethingOccured, MyHandler>();

            //Registering an untyped handler.
            //Will ask for an instance of the type mapped against this bindingkey.
            //server.AttachGenericMessageHandler<GenericEventHandler>("#");

            //Start the server.
            //The infrastructure will be created on the rabbit server and the adapter will start to recieve the messages.
            //server.StartServer();

            Console.ReadLine();

            //Stop the server to dispose the connections to Rabbit.
            //server.StopServer();
        }
        /// <summary>
        /// 设置独特的值
        /// </summary>
        /// <param name="connectionInfo">连接信息</param>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        protected override void SetOnlyHaveValue(ConnectionInfo connectionInfo, string name, string value)
        {
            RabbitConnectionInfo rabbitConnectionInfo = connectionInfo as RabbitConnectionInfo;

            switch (name)
            {
            case "virtualPath":
                rabbitConnectionInfo.VirtualPath = value;

                break;

            case "autoRecovery":
                rabbitConnectionInfo.AutoRecovery = Convert.ToBoolean(value);

                break;

            case "heartbeat":
                rabbitConnectionInfo.Heartbeat = Convert.ToUInt16(value);

                break;
            }
        }
示例#11
0
        /// <summary>
        /// <para>Register all events and its handlers.</para>
        /// <para>Registers an IMessageContext as scoped that can be used to retrive context information.</para>
        /// <para>Registers an ISerializer so you do not need to implement it, JSON is assumed.</para>
        /// <para>Registers a background service for listening to messages from rabbit mq</para>
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <param name="connectionInfo"></param>
        /// <param name="config"></param>
        public static void ConfigureRabbitMessageConsumer(this IServiceCollection serviceCollection, RabbitConnectionInfo connectionInfo, Action <MessageConfig> config)
        {
            var cnfg = new MessageConfig();

            config(cnfg);

            serviceCollection.AddScoped <IRecivedMessageContext, MessageContextHolder>();

            cnfg.MessageHandlers.ToList().ForEach(kv =>
            {
                serviceCollection.AddScoped(kv.Value);
            });

            serviceCollection.AddSingleton(cnfg);
            serviceCollection.TryAddSingleton <RabbitConnectionInfo>(connectionInfo);
            serviceCollection.TryAddSingleton <ISerializer>(new Serializer());
            serviceCollection.TryAddSingleton <IMessageAdapter, RabbitMessageAdapter>();
            serviceCollection.TryAddSingleton <MessageHandlerEngine>();

            serviceCollection.AddHostedService <RabbitMQBackgroundService>();
        }
        /// <summary>
        /// 验证独特的参数集合,如果不通过则抛出对应异常
        /// </summary>
        /// <param name="connectionInfo">连接信息</param>
        protected override void ValidateOnlyHaveParams(ConnectionInfo connectionInfo)
        {
            RabbitConnectionInfo rabbitConnectionInfo = connectionInfo as RabbitConnectionInfo;

            ValidateUtil.ValidateNullOrEmpty(rabbitConnectionInfo.VirtualPath, "虚拟路径");
        }