2013-11-28 22 views
0

我剛剛開始使用Java ee 7,這是我無法想象它是如何神奇地工作的。Java ee jms現場背後的魔力是什麼?

我遵循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:MSG的

@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接口

一個POJO對象

ExpensiveOrderMDB和POJO打包在一個.jar文件中,並部署在本地運行的glassfish服務器中。連接和desitination資源由asadmin創建。

問題是:消費者和生產者如何知道連接和目的地在本地glassfish服務器上可用,以便進行連接併發送/接收消息? (創建連接和目的地的行對本地glassfish服務器沒有任何說明)

回答

0

可能有一個jndi.properties文件,其中定義了glassfish的連接