Ejemplo n.º 1
0
        public void Publish <T>(T message, string exchangeName, string exchangeType, string routeKey)
            where T : class
        {
            if (message == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            try
            {
                channel.ExchangeDeclare(exchangeName, exchangeType, true, false, null);

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(exchangeName, routeKey, properties, sendBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            #region list方案未通过
            ///////////////////list方案--未通过
            //var name = context.RouteData.Values["action"].ToString();
            //var c = defaultObjectsList.Where(u => u.Get().id == name).FirstOrDefault();
            //DefaultObjectPool<Dome> resulCabak = null;
            //foreach (var item in defaultObjectsList)
            //{
            //    var d = item;
            //    var namec = item.Get().id;
            //    if (item.Get().id == name)
            //    {
            //        resulCabak = item;
            //    }
            //}
            //if (resulCabak != null)
            //{
            //    var cResult = resulCabak.Get();
            //    context.Result = cResult.view;
            //    c.Return(cResult);
            //}
            #endregion

            #region 单独实现-通过

            ////////////////////////////////单独实现-通过

            //单个页面测试
            //var Result = defaultPoolWithDemoPolicy.Get();
            //if (Result.id == context.RouteData.Values["action"].ToString())
            //{
            //    context.Result = Result.view;
            //    defaultPoolWithDemoPolicy.Return(Result);
            //}

            #endregion

            /////////////////////////////////继续扩展完善

            Dome Result = null;
            for (int i = 0; i < 3; i++)
            {
                Result = defaultPoolWithDemoPolicy.Get();
                if (Result != null)
                {
                    if (Result.id == context.RouteData.Values["action"].ToString())
                    {
                        context.Result = Result.view;
                        defaultPoolWithDemoPolicy.Return(Result);
                        break;
                    }
                    else
                    {
                        //defaultPoolWithDemoPolicy.Return(Result);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public void Test2()
        {
            var demoPolicy = new DemoPooledObjectPolicy();
            var defaultPoolWithDemoPolicy = new DefaultObjectPool <Demo>(demoPolicy, 1);
            //获取一个对象
            var item1 = defaultPoolWithDemoPolicy.Get();
            //获取一个对象
            var item2 = defaultPoolWithDemoPolicy.Get();

            Assert.True(item1 != item2);
        }
Ejemplo n.º 4
0
        public void PoolTest()
        {
            var p = new DefaultObjectPool <TClass>(new DefaultPooledObjectPolicy <TClass>());

            var a = p.Get();
            var b = p.Get();

            Console.WriteLine(a.Number);
            Console.WriteLine(b.Number);
            p.Return(a);
            var c = p.Get();

            Console.WriteLine(c.Number);
        }
Ejemplo n.º 5
0
    public void DefaultObjectPoolWithDefaultPolicy_GetAnd_ReturnObject_SameInstance()
    {
        // Arrange
        var pool = new DefaultObjectPool <object>(new DefaultPooledObjectPolicy <object>());

        var obj1 = pool.Get();

        pool.Return(obj1);

        // Act
        var obj2 = pool.Get();

        // Assert
        Assert.Same(obj1, obj2);
    }
Ejemplo n.º 6
0
        public void DefaultObjectPool_GetAndReturnObject_SameInstance()
        {
            // Arrange
            var pool = new DefaultObjectPool <List <int> >(new ListPolicy());

            var list1 = pool.Get();

            pool.Return(list1);

            // Act
            var list2 = pool.Get();

            // Assert
            Assert.Same(list1, list2);
        }
Ejemplo n.º 7
0
        public void DefaultObjectPool_Return_RejectedByPolicy()
        {
            // Arrange
            var pool  = new DefaultObjectPool <List <int> >(new ListPolicy());
            var list1 = pool.Get();

            list1.Capacity = 20;

            // Act
            pool.Return(list1);
            var list2 = pool.Get();

            // Assert
            Assert.NotSame(list1, list2);
        }
        public void Publish(AppointmentConfirmedEvent eventToPublish)
        {
            Guard.Against.Null(eventToPublish, nameof(eventToPublish));

            var channel = _objectPool.Get();

            object message = (object)eventToPublish;

            try
            {
                string exchangeName = MessagingConstants.Exchanges.FRONTDESK_VETCLINICPUBLIC_EXCHANGE;
                channel.ExchangeDeclare(exchangeName, "direct", true, false, null);

                var sendBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(
                    exchange: exchangeName,
                    routingKey: "appointment-confirmation",
                    basicProperties: properties,
                    body: sendBytes);
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 9
0
        static string GenerateQualifiedText(IEnumerable <IIdentity> value)
        {
            // ReSharper disable once PossibleMultipleEnumeration
            if (!value.Any())
            {
                return(string.Empty);
            }

            var bld = StringBuilderPool.Get();

            try
            {
                foreach (var elem in value)
                {
                    bld.Append(elem.Name);
                    bld.Append(Encode((byte)elem.Category));
                    bld.Append(Encode((byte)elem.Scope));
                    bld.Append('.');
                }

                return(bld.Extract(..^ 1).ToString());
            }
            finally
            {
                StringBuilderPool.Return(bld);
            }
        }
Ejemplo n.º 10
0
        public Task Publish(EventItem eventItem)
        {
            _ = eventItem ?? throw new ArgumentNullException(nameof(eventItem));
            if (eventItem.Data == null)
            {
                return(Task.CompletedTask);
            }
            var channel = _objectPool.Get();

            try
            {
                channel.ExchangeDeclare(eventItem.Exchange, eventItem.EventType);

                if (eventItem.EventType == EventType.Queue)
                {
                    // 声明queue,防止还没有Consumer的时候消息丢失
                    channel.QueueDeclareAndBind(eventItem.Exchange);
                }


                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(eventItem.Exchange, eventItem.Exchange, properties, eventItem.Data);
                return(Task.CompletedTask);
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 11
0
        public void Open()
        {
            _channel        = _objectPool.Get();
            _replyQueueName = _channel.QueueDeclare().QueueName;
            _consumer       = new EventingBasicConsumer(_channel);

            _props = _channel.CreateBasicProperties();
            var correlationId = Guid.NewGuid().ToString();

            _props.CorrelationId = correlationId;
            _props.ReplyTo       = _replyQueueName;

            _signal = new ManualResetEvent(false);

            _consumer.Received += (model, ea) =>
            {
                var body     = ea.Body;
                var response = Encoding.UTF8.GetString(body);
                if (ea.BasicProperties.CorrelationId == correlationId)
                {
                    _signal.Set();
                    _respQueue.Add(response);
                }
            };
        }
        public ConsumeRabbitMQHostedService(IPooledObjectPolicy <IModel> objectPolicy, IConfiguration Configuration)
        {
            this.Configuration = Configuration;
            string exchangeName = "exchange";

            _objectPool   = new DefaultObjectPool <IModel>(objectPolicy, Environment.ProcessorCount * 1);
            RabbitManager = new RabbitManager(objectPolicy);
            _channel      = _objectPool.Get();
            _channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, true, false);
            _channel.QueueDeclare(StaticParams.ModuleName, true, false, false, null);

            List <Type> handlerTypes = typeof(ConsumeRabbitMQHostedService).Assembly.GetTypes()
                                       .Where(x => typeof(Handler).IsAssignableFrom(x) && x.IsClass && !x.IsAbstract)
                                       .ToList();

            foreach (Type type in handlerTypes)
            {
                Handler handler = (Handler)Activator.CreateInstance(type);
                Handlers.Add(handler);
            }

            foreach (IHandler handler in Handlers)
            {
                handler.QueueBind(_channel, StaticParams.ModuleName, exchangeName);
            }
            _channel.BasicQos(0, 1, false);
        }
Ejemplo n.º 13
0
        public virtual void PushMessage(Message message, QueueConfiguration queueConfiguration)
        {
            string msgJson = JsonConvert.SerializeObject(message);
            var    body    = Encoding.UTF8.GetBytes(msgJson);
            var    channel = _RabbitMQPersistent.Get();

            try
            {
                IBasicProperties properties = channel.CreateBasicProperties();
                var headers = new Dictionary <string, object>();
                properties.Persistent   = true;
                properties.DeliveryMode = 2;
                headers.Add("x-delay", queueConfiguration.Dealy);
                properties.Headers = headers;

                channel.BasicPublish(exchange: queueConfiguration.ExhangeName,
                                     routingKey: queueConfiguration.QueueName,
                                     basicProperties: properties,
                                     body: body);

                _logger.LogPublishing(message);
            }
            finally
            {
                _RabbitMQPersistent.Return(channel);
            }
        }
Ejemplo n.º 14
0
        public void Publish <T>(
            T message, string exchangeName,
            string exchangeType, string routeKey)
        {
            if (message == null)
            {
                return;
            }
            //We create an object pool in the constructor. Before publishing
            //messages to RabbitMQ, we should get a channel from the object pool,
            //then construct the payload.
            var channel = _objectPool.Get();

            try {
                channel.ExchangeDeclare(exchangeName, exchangeType, true, false, null);
                var sendBytes  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;
                channel.BasicPublish(exchangeName, routeKey, properties, sendBytes);
            } catch (Exception ex) {
                throw ex;
            } finally {
                //publishing, we should return this channel object
                //to the object pool whether the publish succeeds or fails.
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 15
0
        public void Send <T>(T message, string exchangeName, string exchangeType, string routeKey) where T : class
        {
            if (message == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            try
            {
                channel.ExchangeDeclare(exchangeName, exchangeType, true, false);

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(exchangeName, routeKey, properties, sendBytes);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Can not send a message to converter service: {ex.Message}");
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 16
0
        public void Publish(IApplicationEvent applicationEvent)
        {
            Guard.Against.Null(applicationEvent, nameof(applicationEvent));

            var channel = _objectPool.Get();

            object message = (object)applicationEvent;

            try
            {
                string exchangeName = MessagingConstants.Exchanges.FRONTDESK_CLINICMANAGEMENT_EXCHANGE;
                channel.ExchangeDeclare(exchangeName, "direct", true, false, null);

                var sendBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(
                    exchange: exchangeName,
                    routingKey: "entity-changes",
                    basicProperties: properties,
                    body: sendBytes);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
    public void Receive(string queueName)
    {
        var channel = _objectPool.Get();

        var consumer = new EventingBasicConsumer(channel);

        consumer.Received += (model, ea) =>
        {
            try
            {
                var body    = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                var order   = System.Text.Json.JsonSerializer.Deserialize <Order>(message);

                Console.WriteLine($"Order: {order.OrderNumber}|{order.ItemName}|{order.Price:N2}");

                channel.BasicAck(ea.DeliveryTag, false);
            }
            catch (Exception ex)
            {
                channel.BasicNack(ea.DeliveryTag, false, true);

                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        };

        channel.BasicConsume(queue: "orderQueue",
                             autoAck: false,
                             consumer: consumer);
    }
Ejemplo n.º 18
0
        public void Publish <T>(T message, string routeKey, Action <IBasicProperties> configureProperties)
            where T : class
        {
            if (message == null)
            {
                throw new RabbitEmptyMessageException("Message is null");
            }

            var channel = _objectPool.Get();

            try
            {
                if (string.IsNullOrEmpty(_exchangeType) || string.IsNullOrEmpty(_exchnageName))
                {
                    throw new RabbitEmptyExchangeSettingsException("You didn't set exchange settings. Before you call Publish() or Call(), you should set exchange settings by SetExchnage() method");
                }

                channel.ExchangeDeclare(_exchnageName, _exchangeType, _isDurable, _autoDelete);

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var props = channel.CreateBasicProperties();
                configureProperties.Invoke(props);

                channel.BasicPublish(_exchnageName, routeKey, props, sendBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 19
0
        public void PublishList <T>(List <EventMessage <T> > message, GenericEnum routeKey) where T : DataEntity
        {
            if (!StaticParams.EnableExternalService)
            {
                return;
            }
            if (message == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            try
            {
                channel.ExchangeDeclare("exchange", ExchangeType.Topic, true, false, null);

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish("exchange", routeKey.Code, properties, sendBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
        public async Task Publish(IEvent @event)
        {
            if (@event == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            var exchangeName = @event.GetType().FullName;

            try
            {
                channel.ExchangeDeclare(exchangeName, ExchangeType.Fanout);

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@event));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                await Task.Run(() =>
                {
                    channel.BasicPublish(exchangeName, "", properties, sendBytes);
                });
            }
            catch (Exception)
            {
                //TODO: Loguear el error pero no bloquear la operación
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 21
0
        public void Publish <T>(T message, string routeKey) where T : class
        {
            if (message == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            try
            {
                channel.QueueDeclare(routeKey, durable: false, exclusive: false, autoDelete: false, arguments: null);


                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish("", routeKey, properties, sendBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 22
0
        public void Publish <T>(T message) where T : class
        {
            if (message == null)
            {
                return;
            }

            var channel = _objectPool.Get();

            try
            {
                _logger.LogInfo("Publishing message to RabbitMQ");

                var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(_rabbitExchangeOptions.Exchange, _rabbitExchangeOptions.RoutingKey, properties, sendBytes);
            }
            catch (Exception ex)
            {
                _logger.LogInfo("Publishing message to RabbitMQ failed");
                throw new RabbitMqException("Service_bus_publish_failed. Exception message: " + ex.Message);
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
Ejemplo n.º 23
0
        public void Test3()
        {
            var demoPolicy = new DemoPooledObjectPolicy();
            var defaultPoolWithDemoPolicy = new DefaultObjectPool <Demo>(demoPolicy, 1);
            //获取一个对象
            var item1 = defaultPoolWithDemoPolicy.Get();

            //将对象扔回池中
            defaultPoolWithDemoPolicy.Return(item1);
            //获取一个对象
            var item2 = defaultPoolWithDemoPolicy.Get();
            //获取一个对象
            var item3 = defaultPoolWithDemoPolicy.Get();

            Assert.True((item1 == item2) && (item3 != item2));
        }
Ejemplo n.º 24
0
        public ListenToServiceWorker(ILogger <ListenToServiceWorker> logger
                                     , IRedisSaveDataStrategy redis
                                     , ISqlServerSaveDataStrategy sqlServer,
                                     IOptions <SiteSettings> siteSettings, IServiceScopeFactory serviceScopeFactory
                                     , IPooledObjectPolicy <IModel> objectPolicy
                                     ) : base(serviceScopeFactory)
        {
            Databases = new List <ISaveDataStrategy>();
            Databases.AddRange(new ISaveDataStrategy[] { sqlServer, redis });


            _siteSettings = siteSettings.Value;
            _logger       = logger;
            _queueName    = _siteSettings.RabbitMQSettings.QueueName;

            _objectPool = new DefaultObjectPool <IModel>(objectPolicy, Environment.ProcessorCount * 2);

            channel = _objectPool.Get();

            Log.Write(_logger, "Listen To RabbitMQ");

            channel.QueueDeclare(queue: _queueName,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            consumer = new AsyncEventingBasicConsumer(channel);
        }
Ejemplo n.º 25
0
        public void Handle(Action <T> action)
        {
            var t = DefaultObjectPool.Get();

            try
            {
                action.Invoke(t);
            }
            catch
            {
                throw;
            }
            finally
            {
                DefaultObjectPool.Return(t);
            }
        }
Ejemplo n.º 26
0
        public static void Initialize()
        {
            //Initialize pool eagerly
            var likes = Enumerable.Range(1, MaximumRetained).Select(x => likesPool.Get()).ToArray();

            foreach (var list in likes)
            {
                likesPool.Return(list);
            }

            var stubs = Enumerable.Range(1, MaximumRetained).Select(x => _accountStubPool.Get()).ToArray();

            foreach (var stub in stubs)
            {
                _accountStubPool.Return(stub);
            }
        }
Ejemplo n.º 27
0
        public void Do(Action <IModel> action)
        {
            var channel = _objectPool.Get();

            try
            {
                action(channel);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
        private void registerWeatherForecastConsumers()
        {
            var channel = _objectPool.Get();

            channel.QueueBind(queue: "web-api",
                              exchange: "web-api.service",
                              routingKey: "webapi.weatherforecast.get");
            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                var             body = ea.Body;
                WeatherForecast wf   = JsonConvert.DeserializeObject <WeatherForecast>(Encoding.UTF8.GetString(body.ToArray()));
                _logger.LogInformation($"############# Received {wf.ToString()}");
            };
            channel.BasicConsume(queue: "web-api",
                                 autoAck: true,
                                 consumer: consumer);
        }
Ejemplo n.º 29
0
        public PooledProducer GetProducer()
        {
            var result = producerObjectPool.Get();

            if (result.Pool == default)
            {
                result.Pool = producerObjectPool;
            }
            return(result);
        }
Ejemplo n.º 30
0
        public ModelWrapper PullModel()
        {
            var result = pool.Get();

            if (result.Pool is null)
            {
                result.Pool = pool;
            }
            return(result);
        }