Take a look at this example:
public boolean sendMessage() throws Exception {
Connection connection = null;
InitialContext initialContext = null;
try {
//Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
//Step 2. Perfom a lookup on the queue
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
//Step 3. Perform a lookup on the Connection Factory
ConnectionFactory cf = (ConnectionFactory)
initialContext.lookup("/ConnectionFactory");
//Step 4.Create a JMS Connection
connection = cf.createConnection();
//Step 5. Create a JMS Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//Step 6. Create a JMS Message Producer
MessageProducer producer = session.createProducer(queue);
//Step 7. Create a Text Message
TextMessage message = session.createTextMessage("This is a text message");
System.out.println("Sent message: " + message.getText());
//Step 8. Send the Message
producer.send(message);
//Step 9. Create a JMS Message Consumer
MessageConsumer messageConsumer = session.createConsumer(queue);
//Step 10. Start the Connection
connection.start();
//Step 11. Receive the message
TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);
System.out.println("Received message: " + messageReceived.getText());
return true;
} finally {
//Step 12. Be sure to close our JMS resources!
if (initialContext != null) {
initialContext.close();
}
if(connection != null) {
connection.close();
}
}
}
You have to make 12 (!!!) steps to send and receive the message correctly. I think that most of the steps could be amended so that JMS spec would provide some default behavior.
Luckily, you can write same code with Camel:
from("bean:myBean?methodName=send").to("jms:queue:exampleQueue");
from("jms:queue:exampleQueue").to("bean:myBean?methodName=receive");
2 comments:
Вот поэтому мне Java и не нравится. Слишком обобщённо и усложнено. Для ловли ошибок на любом уровне наверно полезно..
Артём, это не в языке дело. Делов спеке конкретного стандарта - JMS (JSR914), создатели которого слишком умные дядьки, которые решили что всё должно быть максимально сложно, и не подумали, что для простых сценариев мог бы быть упрощённый API
Post a Comment