JMS_使用ActiveMQ实现消息的发送和接收

一、说明

示例中使用activeMQ-all的jar包实现jms消息的发送和接收,发送端和接收端不依赖与服务器,如果想了解使用服务器配置的方式请参照之前的jsm和MDB的文章。

注意topic消息和queue消息的区别。

二、配置

1、ActiveMQ配置

activemq-web-console的配置不再重复。

2、Maven配置

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
			<version>5.5.0</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>1.6.2</version>
		</dependency>

三、发送方和接收方的代码

1、发送方

public class AMQProducer {
	public static void main(String[] args) throws Exception {
		MessageProducer producer = null;
		Connection connection = null;
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		connection = factory.createConnection();
		ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue queue = session.createQueue("myQueue2");
		producer = session.createProducer(queue);
		// Topic topic = session.createTopic("myTopic2");
		// producer = session.createProducer(topic);
		TextMessage textMessage = session.createTextMessage();
		textMessage.setText("Hello AMQ2");
		producer.send(textMessage);
		producer.close();
		connection.close();
	}
}

2、接收方

public class AMQConsumer {
	public static void main(String[] args) throws Exception {
		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		Connection conn = connFactory.createConnection();
		conn.start();
		Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue queue = session.createQueue("myQueue2");
		MessageConsumer consumer = session.createConsumer(queue);
		// Topic topic = session.createTopic("myTopic2");
		// MessageConsumer consumer = session.createConsumer(topic);
		TextMessage message = (TextMessage) consumer.receive();
		String msg = message.getText();
		System.out.println(msg);
		consumer.close();
		conn.close();
	}
}



你可能感兴趣的:(activemq,jms)