jms是大家在項目中經常用到的技術,而activemq又是開源的jms產品中比較優秀的。在應用JMS處理相關業務時,大家都是構造消息,然後發送到隊列,最後用message監聽器監聽到消息,對消息進行分析處理。在這個過程中,有兩步是比較麻煩和重復的,那就是構造消息和拆解消息。並且這樣與面向對象的思想很是違背。如果這樣做顯然是面向消息數據的,而不是面向對象的。基於以上原因,我向大家介紹一個我在項目中經過實踐的開源框架:lingo.
lingo在JMS中起的主要作用就是對消息的封裝,它讓你可以不必關心消息的構造和拆解,而只需關心你本身的業務邏輯。我將舉一個例子,分別用activemq直接實現和用lingo實現。在這個例子中我用到了spring framework.
=================================Hello.Java===========================
import Java.io.Serializable;
/**Hello.java用來傳遞Java對象
* Author: cjp
* Date: 2005-11-8
* Time: 22:24:02
*/
public class Hello implements Serializable {
private String id;
private Hello hello;
private PointList pointList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Hello getHello() {
return hello;
}
public void setHello(Hello hello) {
this.hello = hello;
}
}
=========================SpringTest .Java========================
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import Javax.jms.*;
/**
*發送JMS消息
*/
public class SpringTest extends AbstractDependencyInjectionSpringContextTests
{
protected String[] getConfigLocations()
{
return new String[]{"file:D:\\wosame\\test\\com\\wosame\\room\\jms\\jms.XML"};
}
public void testSendMessage() throws Exception
{
JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
jmsTemplate.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage message=session.createObjectMessage();
Hello hello=new Hello();
hello.setId("test");
message.setObject(hello);
return message;
}
});
}
}
================================HelloMDP .Java==================================
/**
處理JMS消息
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import Javax.jms.*;
public class HelloMDP implements MessageListener
{
protected Log log = LogFactory.getLog(HelloMDP.class);
public void onMessage(Message message)
{
try
{
ObjectMessage objMessage = (ObjectMessage) message;
Hello hello= (Hello) objMessage.getObject();
System.out.println("hello.getId() = " + hello.getId());
} catch (JMSException e)
{
log.error("Parse failed", e);
}
}
}
================================jms.XML==================================
"http://www.springframework.org/dtd/spring-beans.dtd">