/// <summary> /// 发布消息 /// </summary> /// <param name="exchange"></param> /// <param name="routingKey"></param> /// <param name="message"></param> /// <param name="options"></param> public void Publish(string exchange, string routingKey, string message, ExchangeQueueOptions options = null) { Publish(exchange, new RouteMessage() { Message = message, RoutingKey = routingKey }, options); }
/// <summary> /// 发布消息 /// </summary> /// <param name="exchange"></param> /// <param name="routingKey"></param> /// <param name="messages"></param> /// <param name="options"></param> public void Publish(string exchange, string routingKey, string[] messages, ExchangeQueueOptions options = null) { Publish(exchange, messages.Select(message => new RouteMessage() { Message = message, RoutingKey = routingKey }).ToArray(), options); }
/// <summary> /// 准备连接 /// </summary> /// <param name="options"></param> /// <returns></returns> protected void PrepareExchangeChannel(IModel channel, string exchange, ExchangeQueueOptions options) { if (options.Type == RabbitExchangeType.None) { throw new NotSupportedException($"{nameof(RabbitExchangeType)} must be specified"); } channel.ExchangeDeclare(exchange, options.Type.ToString().ToLower(), options.Durable, options.AutoDelete, options.Arguments ?? new Dictionary <string, object>()); if (options.RouteQueues != null) { foreach (var t in options.RouteQueues) { if (!string.IsNullOrEmpty(t.Queue)) { //这里的exclusive参数表示是否与当前的channel绑定 channel.QueueDeclare(t.Queue, t.Options?.Durable ?? options.Durable, false, t.Options?.AutoDelete ?? options.AutoDelete, t.Options?.Arguments ?? options.Arguments ?? new Dictionary <string, object>()); channel.QueueBind(t.Queue, exchange, t.Route ?? "", options.Arguments ?? new Dictionary <string, object>()); } } } }
/// <summary> /// 发布消息 /// </summary> /// <param name="exchange"></param> /// <param name="routeMessages"></param> /// <param name="options"></param> public void Publish(string exchange, RouteMessage[] routeMessages, ExchangeQueueOptions options = null) { if (string.IsNullOrEmpty(exchange)) { throw new ArgumentException("exchange cannot be empty", nameof(exchange)); } options = options ?? new ExchangeQueueOptions(); if (options.Type == RabbitExchangeType.None) { throw new NotSupportedException($"{nameof(RabbitExchangeType)} must be specified"); } var channel = GetChannel(); PrepareExchangeChannel(channel, exchange, options); foreach (var routeMessage in routeMessages) { var buffer = Encoding.UTF8.GetBytes(routeMessage.Message); channel.BasicPublish(exchange, routeMessage.RoutingKey, null, buffer); } channel.Close(); }
/// <summary> /// 发布消息 /// </summary> /// <param name="exchange"></param> /// <param name="routeMessage"></param> /// <param name="options"></param> public void Publish(string exchange, RouteMessage routeMessage, ExchangeQueueOptions options = null) { Publish(exchange, new RouteMessage[] { routeMessage }, options); }