消息中间件的TOPIC和QUEUE

TOPIC和QUEUE是两种不同的消息机制,常用于消息中间件和分布式系统中。

1. TOPIC
- 在TOPIC中,消息发布者将消息发送到Topic(主题)上,并指定一个主题名称。
- 订阅者可以通过订阅该主题来接收所有传入的消息。
- 消息在订阅者之间进行广播,即所有订阅该主题的订阅者都会收到相同的消息。

2. QUEUE
- 在QUEUE中,消息发布者发送消息到Queue(队列)上,而订阅者从队列中获取并处理这些消息。
- 队列按照FIFO(First in, First Out)的顺序对消息进行排列,即先进入队列的消息被最先处理,后进入队列的消息会等待前面的消息被处理完之后再继续处理。
- 消费者从队列中接收到的每个消息只能由一个消费者处理。

因此,主题适用于发布/订阅模式,即一条消息需要传递给多个消费者,而队列适用于点对点消息传递模式,即一条消息只能被一个消费者处理。

public class ActiveMQController {
	
	@Autowired
	Producer producer;
	
	@Autowired
	@Qualifier("topic")
	Topic topic;
	
	@Autowired
	@Qualifier("queue")
	Queue queue;
	
	@RequestMapping("demo")
	public String demo(){
		return "demo";
	}
	
	@RequestMapping(value="/produce",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public void produce(@ModelAttribute("mail") Mail mail) throws Exception{
		producer.sendMail(queue, mail);
	}
	
	@RequestMapping(value="/topic",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public void topic(@ModelAttribute("mail")Mail mail) throws Exception{
		producer.sendMail(topic, mail);
	}
	
}
@Service("producer")
public class ProducerImpl implements Producer{
	
	@Autowired
    public JmsMessagingTemplate jmsMessagingTemplate;
	
	@Override
	public void sendMail(Destination des, Mail mail) {
		jmsMessagingTemplate.convertAndSend(des, mail);
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_70143756/article/details/131006315