使用jms的pulish alert和subscribe topic示例代码
1. Required lib
Make sure the following three libs in the CLASSPATH: Sonic_XA.jar; mfcontext.jar; Sonic_client.jar.
2. Get JNDI Environment:
Properties prop = new Properties ();
prop.put(Context.INITIAL_CONTEXT_FACTORY, “com.sonicsw.jndi.mfcontext.MFContextFactory");
prop.put(Context.PROVIDER_URL, “tcp://localhost:2506");
//prop.put("com.sonicsw.jndi.mfcontext.domain", "Domain1"); //optional
//prop.put("com.sonicsw.jndi.mfcontext.idleTimeout", "6000"); //optional
//prop.put(Context.SECURITY_PRINCIPAL, "Administrator"); //optional
//prop.put(Context.SECURITY_CREDENTIALS, "Administrator"); //optional
Context context = new InitialContext(prop);
3. Get Connection Factory
ConnectionFactory connFactory =
(ConnectionFactory)context.lookup(“testConnectionFactory”); //the parameter is the jndi name of the Connection //Factory configured in the sonicMQ JNDI.
Connection conn = connFactory.createConnection ();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
5. Create Producer and Message, then send a message
MessageProducer producer = session.createProducer(topic);
Message message = session.createTextMessage();
…………………
…………………//Set message context;
producer.send(session.createTopic(“topicName”), message); //send //message to a specific topic
Create Consumer and Subscribe a message
Topic topic = session.createTopic(“myTopic”);
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(msgListener);//msgListener is an object implements the MessageListener interface;