JMS - 异步消息的使者
时间:2011-01-17 BlogJava Chris.Cui
Java消息服务(JMS)实现了异步消息的传递,在企业级的应用中,极大的简化了异步通信系统的实现,使用消息传递的优点在于保持了系统的松散耦合。
JMS支持点到点(P2P)模式和发布-订阅(pub/sub)模式。点到点消息模式依赖于消息队列概念,它将消息发送到称为队列(Queue)的特定目的地,接受者从队列中获取消息,对其进行处理。发布-订阅模式则是将消息发送到成为主题(Topic)的目的地,使用者通过订阅消息来获取。因此,我们可以简单的将Queue和Topic理解为消息的存储器,或者接受器,通过它将消息转发给消息最终的接收者。对于消息,可以是一个简单的字符串,一段二进制流,或者一个任意的对象,当前JMS支持五种类型的消息:TextMessage、MapMessage、ByteMessage、 StreamMessage、ObjectMessage。
下面来看一段P2P的完整实现,
sender:
Context context = new InitialContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("QueueConnectionFactoryTest");
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) context.lookup("QueueTest");
QueueSender queueSender = queueSession.createSender(queue);
TextMessage message = queueSession.createTextMessage();
message.setText("Hello JMS!");
queueSender.send(message);
queueConnection.close();
Receiver:
Context context = new InitialContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("QueueConnectionFactoryTest");
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) context.lookup("QueueTest");
QueueReceiver queueReceiver = queueSession.createReceiver(queue);
queueConnection.start();
while (true) {
Message m = queueReceiver.receive();
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
System.out.println("Reading message: " + message.getText());
} else {
break;
}
}
queueConnection.close();
JMS - 异步消息的使者(2)
时间:2011-01-17 BlogJava Chris.Cui
由上代码可以看出,sender和receiver的实现基本是相同的,下面我们再来对比一下pub/sub模式的实现,
publisher:
Context context = new InitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("TopicConnectionFactoryTest");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession =
|