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); } } } }
public void QueuePurge(string queueName) { var channel = _objectPool.Get(); try { channel.QueuePurge(queueName); } finally { _objectPool.Return(channel); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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 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 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); } }
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); } }
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); } }
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); } }
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); }
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); } }
public void Handle(Action <T> action) { var t = DefaultObjectPool.Get(); try { action.Invoke(t); } catch { throw; } finally { DefaultObjectPool.Return(t); } }
public void ZeroCapacities() { var pool = new DefaultObjectPool <TestPooledObject>(() => new TestPooledObject(), 0, 0); var origLeased = pool.Lease(); pool.Return(origLeased); Assert.AreNotSame(origLeased, pool.Lease()); }
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); } }
public void Do(Action <IModel> action) { var channel = _objectPool.Get(); try { action(channel); } catch (Exception ex) { throw ex; } finally { _objectPool.Return(channel); } }
public void ObjectIsReused(int sharedCapacity, int threadLocalCapacity) { var pool = new DefaultObjectPool <TestPooledObject>(() => new TestPooledObject(), sharedCapacity, threadLocalCapacity); var origLeased = pool.Lease(); pool.Return(origLeased); Assert.AreSame(origLeased, pool.Lease()); Assert.AreNotSame(origLeased, pool.Lease()); }
public void DisposeCleansSharedPool() { var pool = new DefaultObjectPool <TestPooledObject>(() => new TestPooledObject(), 10, 0); var origLeased = pool.Lease(); pool.Return(origLeased); pool.Dispose(); Assert.AreNotSame(origLeased, pool.Lease()); }
public static object ParseLiteral( InputObjectType type, ObjectValueNode value, InputObjectFactory factory, ITypeConverter converter) { Dictionary <string, object> dict = _dictionaryPool.Get(); try { Parse(type, value, dict, converter); SetDefaultValues(type, dict, converter); return(factory(dict, converter)); } finally { _dictionaryPool.Return(dict); } }
public bool TryGenerateLine(Detail item, out string line) { var sb = _pool.Get(); sb.Append(item.PartnerPartNumber); AddInnerLineData(item, sb); line = sb.ToString(); sb.Clear(); _pool.Return(sb); return(true); }
public void Test1() { var demoPolicy = new DemoPooledObjectPolicy(); var defaultPoolWithDemoPolicy = new DefaultObjectPool <Demo>(demoPolicy, 1); //获取一个对象 var item1 = defaultPoolWithDemoPolicy.Get(); //将对象扔回池中 defaultPoolWithDemoPolicy.Return(item1); //获取一个对象 var item2 = defaultPoolWithDemoPolicy.Get(); Assert.True(item1 == item2); }
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); }
void Start() { // Arrange var pool = new DefaultObjectPool <object>(new DefaultPooledObjectPolicy <object>(), 4); var obj1 = pool.Get(); var obj2 = pool.Get(); pool.Return(obj1); pool.Return(obj2); for (int i = 0; i < 4; ++i) { pool.Return(new object()); } // Act obj2 = pool.Get(); if (obj1 == obj2) { Log.Debug("True"); } }
public void Serialize(ref MessagePackWriter writer, Frame <T> value, MessagePackSerializerOptions options) { ArrayPoolBufferWriter <byte> bodyWriter = objPoolBufferWriterBodies.Get(); try { var formatterT = options.Resolver.GetFormatterWithVerify <T>(); Serialize(ref writer, value.Item, options, bodyWriter, formatterT); } finally { objPoolBufferWriterBodies.Return(bodyWriter); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { mainChannel = channelPool.Get(); while (!stoppingToken.IsCancellationRequested) { consume(await bus.ReceiveAsync()); } checkConsumers(); mainChannel.Close(); channelPool.Return(mainChannel); }
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.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); //string message2 = "Hello World!"; var body = Encoding.UTF8.GetBytes(message.ToJson()); channel.BasicPublish(exchange: "", routingKey: queueName, basicProperties: null, body: body); //channel.QueueDeclare(queue: exchangeName, // durable: false, // exclusive: false, // autoDelete: false, // arguments: null); //var sendBytes = Encoding.UTF8.GetBytes(message.ToJson()); //var properties = channel.CreateBasicProperties(); //properties.Persistent = true; //channel.BasicPublish(exchangeName, routeKey, properties, sendBytes); } catch (Exception ex) { throw ex; } finally { _objectPool.Return(channel); } }