queue可以有多个consumer,但一条消息只能被一个consumer收到
topic也可以有多个consumer,但一条消息可以被所有订阅该消息的consumer收到
topic的多个consumer之间用clientid区分。
activemq客户端只需要导入activemq.jar包即可
发送者示例:
public class ActivemqPublisherTest {
/**
* @param args
* @throws JMSException
*/
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://xxx.xxx.xxx.xxx:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("product_change");
MessageProducer producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
MapMessage mm = session.createMapMessage();
//mm.setString("channelid", "0008");
mm.setString("topicid", "294S0008");
producer.send(mm);
session.close();
connection.stop();
connection.close();
}
}
接收者示例:
public class ActivemqConsumerTest {
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://123.126.62.145:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("product_change");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
//TextMessage tm = (TextMessage) message;
MapMessage m = (MapMessage) message;
try {
System.out.println("Received message: " + message);
System.out.println("Received message: " + m.getString("topicid"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
// session.close();
//
// connection.stop();
//
// connection.close();
}
}