使用ActiveMQ发送接收队列(Queue)消息

Apache ActiveMQ is the most popular and powerful open source messaging and Integration Patterns provider.

  • 下载

进入下载页面:http://activemq.apache.org/activemq-541-release.html,下载zip包

然后启动起来,windows下可以直接运行bin下的activemq.bat

  • 创建发送端

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
QueueConnection connection = factory.createQueueConnection();
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("queue");
QueueSender sender = session.createSender(queue);
TextMessage message = session.createTextMessage();
message.setText("Hello ActiveMQ");
sender.send(message);
connection.close();
  •  创建接收端

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
QueueConnection queueConnection = factory.createQueueConnection();
QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(txtKeyWord.getText());
QueueReceiver receiver = session.createReceiver(queue);
receiver.setMessageListener(new MessageListener() {
	public void onMessage(Message message) {
		if(message instanceof TextMessage){
			TextMessage textMessage = (TextMessage)message;
			try {
				textArea.append(">>" + textMessage.getText() + "\n");
				textArea.setCaretPosition(textArea.getDocument().getLength());
				textMessage.acknowledge();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
});
queueConnection.start();

 

你可能感兴趣的:(apache,html,windows,activemq)