技术点

  1. 同条件均衡消费
  2. 主模式为 生产消费和发布订阅
  3. 生产消费模式queue
  1. 多个生产对多个消费者,消费者ClientID 不同,就会 负载均衡的消费
  2. 消费者ClientiD 相同,那只有一个能消费
  3. 可以根据某个条件进行过滤进行消费。
  1. 发布者可以根据条件发布
  2. 消费者可以无条件消费,这个时候,同条件就得 均衡消费
  3. 消费者可以有条件消费,同条件一致
  1. 发布订阅模式
  1. 多发布,多订阅(订阅都处理一样的消息,从当前消息开始(没有历史消息))
  2. 条件一致,多实例,订阅模式,一样的消息处理
  3. 发布订阅模式,历史消息消费不到
  1. 问题
  1. 要使用mysql 进行 持久化存储
  2. 在实际使用中是以生产消费模式进行的,另外通过队列名称不一样来进行传递消息,进行消息路由等。

Producer

static void Main(string[] args)
{
Console.WriteLine("生产消息并发送!");
var Factory = new ConnectionFactory("tcp://localhost:61616");
using (IConnection connection = Factory.CreateConnection())
{
using (ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge))
{
while (true)
{
// Queue 这种方式是一对一的方法,一个生产者,面对一个消费者(实际上也是多个生产多个消费)
IMessageProducer prod = session.CreateProducer(new ActiveMQQueue(Config.QueuesName));
// 发布订阅模式 多对多
//IMessageProducer prod = session.CreateProducer(new ActiveMQTopic(Config.TopicName));

ITextMessage message = prod.CreateTextMessage();
var guandao = (DateTime.Now.Ticks % 2).ToString();
message.Properties.SetString("bycar", guandao);

if (guandao == "0")
{
message.Properties.SetString("showcar", "true");
message.Text = $"{DateTime.Now} - {Guid.NewGuid()} - showcar";
}
else
{
message.Text = $"{DateTime.Now} - {Guid.NewGuid()}";
}
Console.WriteLine($"发送消息:{message.Text} -管道:{guandao}");
//Console.WriteLine($"发送消息:{message.Text}");
message.Properties.SetString("filter", Config.QueuesName);
prod.Send(message);
Thread.Sleep(1000);
}
}
}
}

Consumer

static void Main(string[] args)
{
Console.WriteLine("获取消息");

var factory = new ConnectionFactory("tcp://localhost:61616");
var guandao = Console.ReadLine();
IConnection connection = factory.CreateConnection();
connection.ClientId = "BuyCarActionListener" + Guid.NewGuid();//消费者 一样的只能有一个
Console.WriteLine($"一个新的消费者:{connection.ClientId}");
connection.Start();
ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);
IMessageConsumer consumer;
IDestination destination = null;
destination = new ActiveMQQueue(Config.QueuesName);
//destination = new ActiveMQTopic(Config.TopicName);
if (guandao == "1" || guandao == "0")
{
consumer = session.CreateConsumer(destination, $"bycar='{guandao}' or showcar=true");
}
else
{
consumer = session.CreateConsumer(destination);
}

consumer.Listener += new MessageListener((message) =>
{
ITextMessage msg = (ITextMessage)message;
Console.WriteLine($"消费到的数据;{msg.Text}");
msg.Acknowledge();
});
Console.ReadLine();
}

ActiveMQ 简单Demo_发送消息

 

ActiveMQ 简单Demo_activemq_02

ActiveMQ 简单Demo_发布订阅_03