两种模式 Point-to-Point (Destination=Queue): 生产者先推送消息到消息中心,消费者读取消息消费;每个消息只能有一个消费者 Publish-and-Subscribe (Destination=Topic): 订阅者先向消息中心订阅topic,发布者推送消息到消息中心,每个订阅者都可获取自从订阅后的所有历史发布消息;同一条消息可能被多个消费者获取持久化 Queue:默认持久化,消息未读取前会在队列中等待读取 Topic:默认非持久化;因为此模式下的消费者只需要接收订阅后的消息,持久化订阅之前的消息是没有意义的;当持久化后,一定要先运行消费者,相当于向MQ订阅,之后当生产者发送消息后,不管当时消费者是否在线,下次消费者连接时,会把没有收过的消息都接收过来代码 在connection.start()方法调用前,需要setDeliveryMode
public class JmsP {
public static final String URL
= "tcp://192.168.179.129:61616";
public static final String TOPIC_NAME
= "topic1";
public static void main(String
[] args
) throws JMSException
{
ActiveMQConnectionFactory factory
= new ActiveMQConnectionFactory(URL
);
Connection connection
= factory
.createConnection();
Session session
= connection
.createSession(false, Session
.AUTO_ACKNOWLEDGE
);
Topic topic
= session
.createTopic(TOPIC_NAME
);
MessageProducer producer
= session
.createProducer(topic
);
producer
.setDeliveryMode(DeliveryMode
.PERSISTENT
);
connection
.start();
for (int i
= 1; i
<= 3; i
++) {
TextMessage textMessage
= session
.createTextMessage("topic1" + i
);
producer
.send(textMessage
);
}
producer
.close();
session
.close();
connection
.close();
}
}