我刚刚开始使用Java ee 7,这是我无法理解它是如何神奇地工作的。
我按照Antonio Goncalves的Beginning Java EE 7一书中的例子。我设法编译和部署第13章(关于JMS)的代码没有任何问题。消息按预期发送和接收,但这让我感到困惑。
源代码是使用者类,生产者类,POJO和MDB类的组合。
这是消费者:
public class OrderConsumer {
public static void main(String[] args) throws NamingException {
// Gets the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
// Loops to receive the messages
System.out.println("\nInfinite loop. Waiting for a message...");
try (JMSContext jmsContext = connectionFactory.createContext()) {
while (true) {
OrderDTO order = jmsContext.createConsumer(topic).receiveBody(OrderDTO.class);
System.out.println("Order received: " + order);
}
}
}
}
制片人:
public class OrderProducer {
public static void main(String[] args) throws NamingException {
if (args.length != 1) {
System.out.println("usage : enter an amount");
System.exit(0);
}
System.out.println("Sending message with amount = " + args[0]);
// Creates an orderDto with a total amount parameter
Float totalAmount = Float.valueOf(args[0]);
OrderDTO order = new OrderDTO(1234l, new Date(), "Serge Gainsbourg", totalAmount);
// Gets the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
try (JMSContext jmsContext = connectionFactory.createContext()) {
// Sends an object message to the topic
jmsContext.createProducer().setProperty("orderAmount", totalAmount).send(topic, order);
System.out.println("\nOrder sent : " + order.toString());
}
}
}
MDB:
@MessageDriven(mappedName = "jms/javaee7/Topic", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "orderAmount > 1000")
})
public class ExpensiveOrderMDB implements MessageListener {
public void onMessage(Message message) {
try {
OrderDTO order = message.getBody(OrderDTO.class);
System.out.println("Expensive order received: " + order.toString());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
封装在实现Serializable
接口
ExpensiveOrderMDB
并且POJO打包在.jar文件中并部署在本地运行的glassfish服务器中。连接和desitination资源由asadmin
创建。
问题是:消费者和生产者如何知道本地glassfish服务器上的连接和目的地是否可用于建立连接并发送/接收消息? (创建连接和目标的行对本地glassfish服务器一无所知)
答案 0 :(得分:0)
可能有一个jndi.properties文件,其中定义了与glassfish的连接