JMS編程模式 |
|
消息形式: 點對點為兩個客戶之間建立消息隊列,使兩個客戶端之間通過隊列實現點對點的消息傳遞 注:類似數據結構里的隊列,先進先出 主題消息,在消息中間件上建立一個主題,沒個客戶端都可已向這個主題發送消息,接受消息 注:類似廣播的方式 開發流程:
1.創建一個JNDI上下文 Context init initCtx =new InitialContext(env); 2.查找創建JMS連接使用的工廠類(Connnect Factory) 對于主題消息: Object tmp=initCtx.lookup(“Connnect Factory”); TopicConnectionFactory tcf=( TopicConnectionFactory) tmp; 對于點對點消息: Object tmp=initCtx.lookup(“Connnect Factory”); QueueConnectionFactory tcf=( QueueConnectionFactory) tmp; 3.查找JMS的目標對象(Destination) 對于主題消息: Topic topic=(Topic)iniCtx.lookup(“topic/testTopic”); 對于點對點消息: Queue queue (Queue)iniCtx.lookup(“queue /A”); 4.創建JMS連接(Connection) 對于主題消息: TopicConnection conn=tcp.createTopicConnection(); 對于點對點消息: QueueConnection conn=tcp.createQueueConnection (); 5.創建JMS會話(session) 對于主題消息: TopicSession session=conn.createTopicSession(fasle,Session.AUTO_ACKNOWLEDGE); 對于點對點消息: QueueSession session= conn.createQueueSession(true,0); 6.創建消息的生產和消費者 生產者: 對于主題消息: TopicPublisher publisher=session.createPublisher(topic); 對于點對點消息: QueueSender sender = session.createSender (queue); 消費者: 對于主題消息: TopicSubscriber subscriber=session.createSubscriber (topic); 對于點對點消息: QueueReceiver receiver= session.createReceiver (queue); 7.注冊消息的監聽者 對于主題消息: TextListener listener=new TextListener(); subscriber.setMessageListener(listener); 對于點對點消息: TextListener listener=new TextListener(); receiver.setMessageListener(listener); 8.開始JMS的連接 conn.start(); 9.發送和接受消息 發送消息: 對于主題消息: publisher.publish(message); 對于點對點消息: sender.send(message); 接受消息: 對于主題消息: Message msg= subscriber.receive(); 對于點對點消息: Message msg= receiver.receive(1000); 10.停止和關閉JMS連接 conn.stop(); session.close(); conn.close(); |