要在.NET中使用ActiveMQ,可以使用Apache.NMS.ActiveMQ库。以下是一个代码示例,演示如何使用ActiveMQ发送和接收消息:
首先,确保已安装Apache.NMS.ActiveMQ库。可以使用NuGet包管理器安装它。
发送消息:
using Apache.NMS;
using Apache.NMS.ActiveMQ;
public class MessageSender
{
private const string ActiveMQUri = "tcp://localhost:61616";
private const string QueueName = "MyQueue";
public void SendMessage(string message)
{
// 创建连接工厂
IConnectionFactory factory = new ConnectionFactory(ActiveMQUri);
// 创建连接
using (IConnection connection = factory.CreateConnection())
{
connection.Start();
// 创建会话
using (ISession session = connection.CreateSession())
{
// 创建目标(队列)
IDestination destination = session.GetQueue(QueueName);
// 创建生产者
using (IMessageProducer producer = session.CreateProducer(destination))
{
// 创建消息
ITextMessage textMessage = session.CreateTextMessage(message);
// 发送消息
producer.Send(textMessage);
}
}
}
}
}
接收消息:
using Apache.NMS;
using Apache.NMS.ActiveMQ;
public class MessageReceiver
{
private const string ActiveMQUri = "tcp://localhost:61616";
private const string QueueName = "MyQueue";
public void ReceiveMessage()
{
// 创建连接工厂
IConnectionFactory factory = new ConnectionFactory(ActiveMQUri);
// 创建连接
using (IConnection connection = factory.CreateConnection())
{
connection.Start();
// 创建会话
using (ISession session = connection.CreateSession())
{
// 创建目标(队列)
IDestination destination = session.GetQueue(QueueName);
// 创建消费者
using (IMessageConsumer consumer = session.CreateConsumer(destination))
{
// 接收消息
IMessage message = consumer.Receive();
if (message is ITextMessage textMessage)
{
// 处理消息
Console.WriteLine("Received message: " + textMessage.Text);
}
}
}
}
}
}
使用示例:
MessageSender sender = new MessageSender();
sender.SendMessage("Hello ActiveMQ!");
MessageReceiver receiver = new MessageReceiver();
receiver.ReceiveMessage();
这个示例演示了如何在.NET中使用ActiveMQ发送和接收文本消息。你可以根据自己的需求进行调整和扩展。