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==================================
/p>
"http://www.springframework.org/dtd/spring-beans.dtd">