本文整理汇总了C#中RabbitMQ.Client.ConnectionFactory类的典型用法代码示例。如果您正苦于以下问题:C# ConnectionFactory类的具体用法?C# ConnectionFactory怎么用?C# ConnectionFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ConnectionFactory类属于RabbitMQ.Client命名空间,在下文中一共展示了ConnectionFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Telegraph
public Telegraph()
{
var connectionFactory = new ConnectionFactory { HostName = "localhost", VirtualHost = "test" };
_connection = connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
_consumer = new QueueingBasicConsumer(_channel);
}
示例2: RabbitMqEventConsumer
/// <summary>
/// Initializes a new instance of the <see cref="RabbitMqEventConsumer"/> class.
/// </summary>
/// <param name="connectionFactory">The connection factory.</param>
/// <param name="exchangePath">The exchange path.</param>
/// <param name="queue">The queue.</param>
public RabbitMqEventConsumer(ConnectionFactory connectionFactory, string exchangePath, string queue)
{
_active = 1;
_connection = connectionFactory.CreateConnection();
_model = _connection.CreateModel();
_queue = _model.QueueDeclare(queue, true, false, false, new Hashtable());
// bind the queue to an exchange if specified
if (exchangePath != null)
{
_model.QueueBind(_queue, exchangePath, string.Empty);
}
EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer();
eventingBasicConsumer.Received += HandleEvent;
_model.BasicConsume(_queue, true, eventingBasicConsumer);
#if false
_subscription = new Subscription(_model, _queue, true);
var thread = new Thread(ReceiveEvents);
thread.IsBackground = true;
thread.Name = "rabbitmq:consumer";
thread.Start();
#endif
var uriBuilder = new UriBuilder(
"rabbitmq",
connectionFactory.HostName,
connectionFactory.Port,
queue);
Uri = uriBuilder.Uri;
}
示例3: CreateConnectionFactoryAsync
private async Task<ConnectionFactory> CreateConnectionFactoryAsync(Uri uri, CancellationToken cancellationToken)
{
using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false))
{
ConnectionFactory connectionFactory;
if (_connectionFactories.TryGetValue(uri, out connectionFactory))
{
return connectionFactory;
}
_log.Verbose("Creating RabbitMQ connection factory to {0}", uri.Host);
connectionFactory = new ConnectionFactory
{
Uri = uri.ToString(),
UseBackgroundThreadsForIO = true, // TODO: As soon as RabbitMQ supports async/await, set to false
TopologyRecoveryEnabled = true,
AutomaticRecoveryEnabled = true,
ClientProperties = new Dictionary<string, object>
{
{ "eventflow-version", typeof(RabbitMqConnectionFactory).Assembly.GetName().Version.ToString() },
{ "machine-name", Environment.MachineName },
},
};
_connectionFactories.Add(uri, connectionFactory);
return connectionFactory;
}
}
示例4: Main
private static void Main(string[] args)
{
Console.WriteLine("Logger waiting for messages...");
var factory = new ConnectionFactory { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(ExchangeName, "topic");
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queueName, ExchangeName, "ewk.#");
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queueName, true, consumer);
int logEntry = 0;
Console.WriteLine("Waiting for work - press <ctrl-c> to shut down...");
while (true)
{
var message = consumer.Queue.Dequeue();
var body = message.Body;
var contents = Encoding.UTF8.GetString(body);
Console.WriteLine("[{0}:{1:yyyyMMdd-HHmmss.fffff}] {2}",
logEntry++, DateTimeOffset.Now, contents);
}
}
}
}
示例5: WorkQueues
private static void WorkQueues()
{
var connectionFactory = new ConnectionFactory
{
HostName = "localhost"
};
using (var connection = connectionFactory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "task_queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var message = "message...";
var body = Encoding.UTF8.GetBytes(message);
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "",
routingKey: "task_queue",
basicProperties: properties,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
示例6: Main
public static int Main(string[] args)
{
if (args.Length < 1) {
Console.Error.WriteLine("Usage: ShutdownableClient <uri> [<secondsdelay>]");
Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
Console.Error.WriteLine("Parameters:");
Console.Error.WriteLine(" <uri> = \"amqp://user:[email protected]:port/vhost\"");
return 2;
}
ConnectionFactory cf = new ConnectionFactory();
cf.Uri = args[0];
using (IConnection conn = cf.CreateConnection()) {
using (IModel ch = conn.CreateModel()) {
object[] callArgs = new object[1];
if (args.Length > 1) {
callArgs[0] = double.Parse(args[1]);
} else {
callArgs[0] = (double) 0.0;
}
SimpleRpcClient client = new SimpleRpcClient(ch, "ShutdownableServer");
client.TimeoutMilliseconds = 5000;
client.TimedOut += new EventHandler(TimedOutHandler);
client.Disconnected += new EventHandler(DisconnectedHandler);
object[] reply = client.Call(callArgs);
if (reply == null) {
Console.WriteLine("Timeout or disconnection.");
} else {
Console.WriteLine("Reply: {0}", reply[0]);
}
}
}
return 0;
}
示例7: Test
public override void Test(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare("logs", "fanout");
var queueName = channel.QueueDeclare().QueueName;
//The meaning of a binding key depends on the exchange type. The fanout exchanges,
//which we used previously, simply ignored its value
channel.QueueBind(queueName, "logs", "");
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queueName, true, consumer);
Console.WriteLine("接收消息:");
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Recevied:" + message);
}
}
}
}
示例8: Main
public static int Main(string[] args)
{
if (args.Length < 1) {
Console.Error.WriteLine("Usage: Subscriber <uri> [<message count>]");
Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
Console.Error.WriteLine("Parameters:");
Console.Error.WriteLine(" <uri> = \"amqp://user:[email protected]:port/vhost\"");
return 2;
}
string serverAddress = args[0];
long msgCount = (args.Length > 1) ? int.Parse(args[1]) : 10;
ConnectionFactory cf = new ConnectionFactory();
cf.Uri = serverAddress;
using (IConnection conn = cf.CreateConnection()) {
using (IModel ch = conn.CreateModel()) {
string queueName = ensureQueue(ch);
/* We'll consume msgCount message twice: once
using Subscription.Next() and once using the
IEnumerator interface. So, we'll send out
2*msgCount messages. */
sendMessages(ch, queueName, 2*msgCount);
using (Subscription sub = new Subscription(ch, queueName)) {
blockingReceiveMessages(sub, msgCount);
enumeratingReceiveMessages(sub, msgCount);
}
}
}
return 0;
}
示例9: Main
public static void Main(string message)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "Queue1",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var body = Encoding.Unicode.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "Queue1",
basicProperties: null,
body: body);
Debug.WriteLine(" [x] Sent {0}", message);
}
}
}
示例10: call_me_from_child_constructor
//
// This function (call_me_from_child_constructor()) would:
// - extract mongodb-related parameters
// - prepare mongodb connection (actually the result will be "mongodb_channel")
//
// It must be called from child class (from response itself) after child extracts rabbitmq_parameters_bson
// document by parsing command line. This code can not go into constructor, since we need the child to take
// some actions prior to this code. It is not elegant, but works!
//
public void call_me_from_child_constructor() // when stuff for messaging is parsed from cmd line
{
// extract rabbitmq parameters
//
exchange_name = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["exchange_name"].ToJson());
string exchange_type = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["exchange_type"].ToJson());
ConnectionFactory conn_factory = new ConnectionFactory();
conn_factory.HostName = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["host_name"].ToJson());
conn_factory.UserName = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["user_name"].ToJson());
conn_factory.Password = BsonSerializer.Deserialize<string>(rabbitmq_parameters_bson["password"].ToJson());
// extract required storage_service parameters
//
//string queue_name = storage_service_parameters["queue_name"];
// create rabbitmq connection
IConnection conn = conn_factory.CreateConnection();
// create channel
mongodb_channel = conn.CreateModel();
// declare rabbitmq exchange
mongodb_channel.ExchangeDeclare(exchange_name,
exchange_type,
false, // durable
false, // autodelete
null); // args
mongodb_msg_props = mongodb_channel.CreateBasicProperties();
mongodb_msg_props.ContentType = "application/json"; // "text/plain";
}
示例11: Main
static void Main(string[] args)
{
var connectionFactory = new ConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
channel.ExchangeDeclare("topic-exchange-example", ExchangeType.Topic, false, true, null);
channel.QueueDeclare("log", false, false, true, null);
channel.QueueBind("log", "topic-exchange-example", "*.Personal.*");
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("log", true, consumer);
Console.WriteLine("I am the Personal Consumer");
while (true)
{
try
{
var eventArgs = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
string message = Encoding.UTF8.GetString(eventArgs.Body);
Console.WriteLine(string.Format("{0} - {1}", eventArgs.RoutingKey, message));
}
catch (EndOfStreamException)
{
// The consumer was cancelled, the model closed, or the connection went away.
break;
}
}
channel.Close();
connection.Close();
}
示例12: Should_be_able_to_republish_message
public void Should_be_able_to_republish_message()
{
var serializer = new JsonSerializer();
var error = serializer.BytesToMessage<Error>(Encoding.UTF8.GetBytes(errorMessage));
var connectionFactory = new ConnectionFactory
{
HostName = "localhost",
UserName = "guest",
Password = "guest"
};
using (var connection = connectionFactory.CreateConnection())
using (var model = connection.CreateModel())
{
try
{
model.ExchangeDeclarePassive(error.Exchange);
var properties = model.CreateBasicProperties();
error.BasicProperties.CopyTo(properties);
var body = Encoding.UTF8.GetBytes(error.Message);
model.BasicPublish(error.Exchange, error.RoutingKey, properties, body);
}
catch (OperationInterruptedException)
{
Console.WriteLine("The exchange, '{0}', described in the error message does not exist on '{1}', '{2}'",
error.Exchange, connectionFactory.HostName, connectionFactory.VirtualHost);
}
}
}
示例13: Main
static void Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
Console.WriteLine("EasyNetQ.LogReader");
Console.WriteLine("Usage:");
Console.WriteLine("EasyNetQ.LogReader.exe <rabbitMqServer> [<vhost>]");
return;
}
var connectionFactory = new ConnectionFactory
{
HostName = args[0],
VirtualHost = args.Length == 2 ? args[1] : "/"
};
using (var connection = connectionFactory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(
logReaderQueue, // name
false, // durable
true, // exclusive
true, // autoDelete
null); // arguments
channel.QueueBind(logReaderQueue, amqpLogExchange, "*");
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(logReaderQueue, false, consumer);
Console.WriteLine("EasyNetQ.LogReader");
Console.WriteLine("Listening to log");
while (true)
{
try
{
var e = (RabbitMQ.Client.Events.BasicDeliverEventArgs) consumer.Queue.Dequeue();
var logMessage = Encoding.UTF8.GetString(e.Body);
Console.WriteLine(logMessage);
channel.BasicAck(e.DeliveryTag, false);
}
catch (Exception exception)
{
// The consumer was removed, either through
// channel or connection closure, or through the
// action of IModel.BasicCancel().
Console.WriteLine(exception);
Console.WriteLine();
Console.WriteLine("Connection closed.");
break;
}
}
}
}
示例14: Run
public static void Run()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "logs", type: "fanout");
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");
Console.WriteLine(" [*] Waiting for logs.");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] {0}", message);
};
string basicConsume = channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
示例15: GetMQAlarmID
public int GetMQAlarmID()
{
int alarmID = 0;
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "alarm",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queue: "alarm",
noAck: true,
consumer: consumer);
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
alarmID = Convert.ToInt32(message);
}
}
return alarmID;
}