使用Spring JMS簡化非同步訊息處理

gudesheng發表於2008-01-03

http://www.onjava.com/lpt/a/6490

這片文章介紹了Spring是如何簡化非同步訊息呼叫的,它通過一個貸款的例子來說Spring是如何減少

開發中的量的。

下面是傳統開發需要的程式碼量

public void sendMessage() {    queueName = "queue/CreditRequestSendQueue";    System.out.println("Queue name is " + queueName);    /*     * Create JNDI Initial Context     */    try {        Hashtable env = new Hashtable();        env.put("java.naming.factory.initial",            "org.jnp.interfaces.NamingContextFactory");        env.put("java.naming.provider.url","localhost");        env.put("java.naming.factory.url.pkgs",            "org.jnp.interfaces:org.jboss.naming");        jndiContext = new InitialContext(env);    } catch (NamingException e) {        System.out.println("Could not create JNDI API " +            "context: " + e.toString());    }    /*     * Get queue connection factory and queue objects from JNDI context.     */    try {        queueConnectionFactory = (QueueConnectionFactory)        jndiContext.lookup("UIL2ConnectionFactory");        queue = (Queue) jndiContext.lookup(queueName);    } catch (NamingException e) {        System.out.println("JNDI API lookup failed: " +            e.toString());    }    /*     * Create connection, session, sender objects.     * Send the message.     * Cleanup JMS connection.     */    try {        queueConnection =            queueConnectionFactory.createQueueConnection();        queueSession = queueConnection.createQueueSession(false,                Session.AUTO_ACKNOWLEDGE);        queueSender = queueSession.createSender(queue);        message = queueSession.createTextMessage();        message.setText("This is a sample JMS message.");        System.out.println("Sending message: " + message.getText());        queueSender.send(message);    } catch (JMSException e) {        System.out.println("Exception occurred: " + e.toString());    } finally {        if (queueConnection != null) {            try {                queueConnection.close();            } catch (JMSException e) {}        }    }}
 
然後是Spring的程式碼
public void send() {    try {        ClassPathXmlApplicationContext appContext = new 
ClassPathXmlApplicationContext(new String[] {                "spring-jms.xml"});        System.out.println("Classpath loaded");        JMSSender jmsSender = (JMSSender)appContext.getBean("jmsSender");        jmsSender.sendMesage();        System.out.println("Message sent using Spring JMS.");    } catch(Exception e) {        e.printStackTrace();    }}
表面上看Spring獲勝,程式碼少了很多,但是我們再來看看Spring配置的XML
                org.jnp.interfaces.NamingContextFactory                            localhost                            org.jnp.interfaces:org.jboss.naming            
UIL2ConnectionFactory
queue/CreditRequestSendQueue
queue/CreditReqeustReceiveQueue
30000
 
我們開始認清Spring的真面目把。無厘頭的配置,XML的夢魘。從一種混亂到另一種還亂。
 
 


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=607922


相關文章