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