RabbitMqHelper message queue helper

using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQ_Send
{
class ConfigModel
{
}

enum ExchangeTypeEnum public
{
/// <Summary>
/// not process routing keys. You simply need to bound the queues to the switch. Send a message to the switch are forwarded to all queues bound with the switch.
/// like subnet broadcast, the hosts in each subnet have received a copy of the message. Fanout switch forwards messages is the fastest.
/// </ Summary>
fanout =. 1,

/// <Summary>
/// process routing keys. A queue needs to be bound to the switch, and requires that a particular message routing keys exact match
///. This is a complete match. If a queue is bound to claim routing keys "dog", the switch
/// only is labeled "dog" messages are forwarded, it does not forward dog.puppy, does not deliver dog.guard, only forwarding dog.
/// </ Summary>
Direct = 2,

/// <Summary>
/// routing key and a matching pattern. At this time, a queue needs to be bound to the model.
/// "#" symbol matches one or more words, the symbol "*" matches a word more, no less.
/// Thus "audit. #" Can be matched to "audit.irs.corporate", but "audit. *" To only match "audit.irs"
/// </ Summary>
Topic =. 3,

header = 4
}


/// <Summary>
/// data processing is performed after
/// </ Summary>
public enum ProcessingResultsEnum
{
/// <Summary>
/// successfully processed
/// </ Summary>
the Accept,

/// <Summary>
/// may retry the error
/// </ Summary>
the Retry,

/// <Summary>
/// no retry error
/// </ Summary>
Reject,
}

/// <summary>
configuration information message queue ///
/// </ Summary>
public class RabbitMqConfigModel
{
#region Host
/// <summary>
/// server IP address
/// </ Summary>
public String IP {get; set;}

/// <Summary>
/// server port, the default is 5672
/// </ Summary>
public int {Port GET; SET;}

/// <Summary>
/// Login
/// </ Summary>
public String UserName {GET; SET;}

/// <Summary>
/// password
/// </ Summary>
public String {Password GET; SET;}
/// <Summary>
/// virtual host name
/// </ Summary>
public String {VirtualHost GET; SET;}
#endregion

#region Queue
/// <summary>
/// 队列名称
/// </summary>
public string QueueName { get; set; }

/// <Summary>
/// whether the queue is persistent
/// </ Summary>
public BOOL DurableQueue {GET; SET;}
#endregion

#region exchange
/// <summary>
/// 路由名称
/// </summary>
public string ExchangeName { get; set; }

/// <Summary>
/// route Enumerated
/// </ Summary>
public ExchangeTypeEnum The ExchangeType {GET; SET;}

/// <Summary>
/// route keywords
/// </ Summary>
public String RoutingKey {GET; SET;}

#endregion

Message #region
/// <Summary>
/// whether the queue message persistence
/// </ Summary>
public BOOL DurableMessage {GET; SET;}
#endregion
}
/// <Summary>
/// base class
/ // </ Summary>
public class BaseService
{

public static IConnection _connection;

/// <Summary>
/// server configuration
/// </ Summary>
public RabbitMqConfigModel RabbitConfig {GET; SET;}


#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="config"></param>
public BaseService(RabbitMqConfigModel config)
{
try
{
RabbitConfig = config;
CreateConn();
}
catch (Exception)
{
throw;
}
}
#endregion

#region method
#region initialization
/// <Summary>
/// to create a connection
/// </ Summary>
public void CreateConn ()
{
the ConnectionFactory the ConnectionFactory CF2 = new new ();
cf.Port = RabbitConfig.Port; // server port
cf.Endpoint = new AmqpTcpEndpoint (new Uri ( "amqp: //" + RabbitConfig.IP + "/")); // server ip
cf.username = RabbitConfig.UserName; // login account
cf.Password = RabbitConfig. Password; // login account
cf.VirtualHost = RabbitConfig.VirtualHost; // virtual host
cf.RequestedHeartbeat = 60; // Web Hosting

_connection = cf.CreateConnection();
}
#endregion

Send message #region
/// <Summary>
/// send message, generic
/// </ Summary>
/// <typeParam name = "T"> </ typeParam>
/// <param name = "Message" > </ param>
/// <Returns> </ Returns>
public BOOL the Send <T> (T messageInfo, String errMsg An REF)
{
IF (messageInfo == null)
{
errMsg An = "message object can not be null";
return to false ;
}
String value = JsonConvert.SerializeObject (messageInfo);
return the send (value, REF errMsg An);
}
/// <Summary>
/// send a message, string type
/// </ Summary>
/// <param name = "Message"> </ param>
/// <param name = "errMsg An"> </param>
/// <returns></returns>
public bool Send(string message, ref string errMsg)
{
if (string.IsNullOrEmpty(message))
{
errMsg = "消息不能为空";
return false;
}
try
{
if (!_connection.IsOpen)
{
CreateConn();
}
using (var channel = _connection.CreateModel())
{
//推送消息
byte[] bytes = Encoding.UTF8.GetBytes(message);

= Channel.CreateBasicProperties the Properties IBasicProperties ();
properties.DeliveryMode = Convert.ToByte (RabbitConfig.DurableMessage 2:? 1); // supports persistent data

IF (String.IsNullOrEmpty (RabbitConfig.ExchangeName))
{
// use custom routing
channel.ExchangeDeclare (RabbitConfig.ExchangeName, RabbitConfig.ExchangeType.ToString (), RabbitConfig.DurableMessage, to false, null);
channel.BasicPublish ( "" , RabbitConfig.QueueName, Properties, bytes);
}
the else
{
// declare the message queue, and to be persistent, if the name of the queue does not exist, the system automatically creates, without any cover
channel.QueueDeclare (RabbitConfig. the QueueName, RabbitConfig.DurableQueue, to false, to false, null);
channel.BasicPublish (RabbitConfig.ExchangeName, RabbitConfig.RoutingKey, Properties, bytes);
}
return to true;
}

}
catch (Exception ex)
{
errMsg = ex.Message;
return false;
}
}
#endregion
}
public class RabbitBasicService : BaseService
{

/// <summary>
/// 构造函数
/// </summary>
/// <param name="config"></param>
public RabbitBasicService(RabbitMqConfigModel config)
: base(config)
{ }


/// <Summary>
/// accept message, using the processing Action
/// </ Summary>
/// <typeParam name = "T"> </ typeParam>
/// <param name = "Method"> < / param>
public void the Receive <T> (Func <String, BOOL> Method)
{
the try
{
the using (var = _connection.CreateModel Channel ())
{
// declare queue
channel.QueueDeclare (RabbitConfig.QueueName, RabbitConfig.DurableQueue, false , to false, null);
// use routing
IF) (String.IsNullOrEmpty (RabbitConfig.ExchangeName!)
{
// declare routing
channel.ExchangeDeclare (RabbitConfig.ExchangeName, RabbitConfig.ExchangeType.ToString (), RabbitConfig.DurableQueue);
// switch queues and bindings
channel.QueueBind(RabbitConfig.QueueName, RabbitConfig.ExchangeName, RabbitConfig.RoutingKey);
}

// Input 1, if it receives a message, but does not answer, then the client does not receive the next message
channel.BasicQos (0, 1, to false);
// definition of a consumer on the queue
var customer = new QueueingBasicConsumer (Channel);
// var = Customer new new EventingBasicConsumer (Channel);

// consumer queue, and set the answer mode to an active response program
channel.BasicConsume (RabbitConfig.QueueName, false, customer) ;

the while (to true) // Timer
{
// blocking function, obtain the message queue
ProcessingResultsEnum processingResult = ProcessingResultsEnum.Retry;
ulong deliveryTag = 0;
the try
{
//Thread.Sleep(10);

customer.Queue.Dequeue EA = var ();
deliveryTag = ea.DeliveryTag;
byte [] bytes = ea.Body;
String = Encoding.UTF8.GetString body (bytes);
// T = JsonConvert.DeserializeObject info <T> ( body);
Method (body);
processingResult = ProcessingResultsEnum.Accept;
}
the catch (Exception EX)
{
processingResult = ProcessingResultsEnum.Reject; // not be processed in error
}
the finally
{
Switch (processingResult)
{
Case ProcessingResultsEnum.Accept:
// reply confirmation process successfully
channel.BasicAck (deliveryTag,
false); // information processing singled
BREAK;
Case ProcessingResultsEnum.Retry:
// an error has occurred, but can also be re-submitted to the queue reallocation
channel.BasicNack (deliveryTag, false, to true);
BREAK;
Case ProcessingResultsEnum.Reject:
// fatal error has occurred, can not continue, this situation should write a log or send a message to notify the administrator
channel.BasicNack (deliveryTag, false, false );
// write the log
BREAK;
}
}
}

}
}
catch (Exception ex)
{
}
}


}
#Endregion
}

Guess you like

Origin www.cnblogs.com/request/p/11237088.html