JMS - 异步消息的使者[Java编程]
本文“JMS - 异步消息的使者[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
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 - 异步消息的使者[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |