发送消息
public void sessionSendMessage() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://127.0.0.1:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("user");
MessageProducer messageProducer = session.createProducer(queue);
TextMessage textMessage = session.createTextMessage("hello!!!");
String uuid = UUID.randomUUID().toString();
textMessage.setJMSCorrelationID(uuid);
textMessage.setStringProperty("type", "C");
messageProducer.send(textMessage);
System.out.println("发送完成");
connection.start();
MessageConsumer consumer = session.createConsumer(queue, "JMSCorrelationID='" + uuid + "' and type='P'");
consumer.setMessageListener(message -> {
try {
String text = ((TextMessage) message).getText();
System.out.println(text);
} catch (JMSException e) {
e.printStackTrace();
}
});
}
接收消息
public void sessionReceiveMessage() throws Exception {
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnecti
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://127.0.0.1:61616");
activeMQConnectionFactory.setTrustAllPackages(true);
Connection connection = activeMQConnectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE
connection.start();
Queue queue = session.createQueue("user");
MessageConsumer consumer = session.createConsumer(queue, "type='C'");
consumer.setMessageListener(message -> {
try {
String text = ((TextMessage) message).getText();
System.out.println(text);
} catch (JMSException e) {
e.printStackTrace();
}
try {
MessageProducer producer = session.createProducer(queue);
TextMessage textMessage = session.createTextMessage("true");
textMessage.setJMSCorrelationID(message.getJMSCorrelationID());
textMessage.setStringProperty("type", "P");
producer.send(textMessage);
System.out.println("回复完成");
} catch (JMSException e) {
e.printStackTrace();
}
});
}