package com.landingbj.topic;
import javax.jms.*; import javax.naming.InitialContext; import javax.naming.NamingException;
import com.landingbj.util.Tool;
public class MessageReceiver { public final static String JMS_FACTORY = "JMSConnectionFactory"; public final static String TOPIC = "SevenTopic";
public static void main(String[] args) throws NamingException { Tool tool = new Tool(); InitialContext context = tool.getInitialContext(); TopicSession session = null; TopicConnection connection = null; try { TopicConnectionFactory factory = (TopicConnectionFactory) context .lookup(JMS_FACTORY); connection=(TopicConnection) factory.createTopicConnection(); connection.start(); session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = (Topic) context.lookup(TOPIC); TopicSubscriber subscriber=session.createSubscriber(topic); TextMessage message=(TextMessage) subscriber.receive(); System.out.println(message.getText()); subscriber.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { System.out.println(((TextMessage)msg).getText()); } catch (JMSException e) { e.printStackTrace(); } } }); } catch (JMSException e) { e.printStackTrace(); }finally{ try { session.close(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } }
} |