MessageSender.java
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:1k
源码类别:
Java编程
开发平台:
Java
- package day21ex.messagesender;
- import java.io.*;
- import java.util.*;
- import javax.transaction.*;
- import javax.naming.*;
- import javax.jms.*;
- import javax.ejb.*;
- public class MessageSender{
- public final static String JMS_FACTORY =
- "java:comp/env/jms/TopicConnectionFactory";
- public final static String TOPIC =
- "java:comp/env/jms/OrderVerifierTopic";
- public void sendAMessage(Context jndiCtx, String msg) {
- TopicConnection tConnect = null;
- try {
- TopicConnectionFactory tFactory =
- (TopicConnectionFactory) jndiCtx.lookup(JMS_FACTORY);
- Topic t = (Topic)jndiCtx.lookup(TOPIC);
- tConnect =
- tFactory.createTopicConnection();
- TopicSession session = tConnect.createTopicSession(false,
- QueueSession.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = session.createPublisher(t);
- TextMessage jmsMsg = session.createTextMessage();
- jmsMsg.setText(msg);
- publisher.publish(jmsMsg);
- print("Message sent to the topic:" + msg);
- }catch (Exception e) {
- e.printStackTrace();
- throw new EJBException("MessageSender:sendAMessage: Error!",e);
- } finally {
- try {
- if( tConnect != null ) {
- tConnect.close();
- }
- } catch(Exception e) {}
- }
- }
- void print(String s) {
- System.out.println("MessageSender:"+ s);
- }
- }