<1>.配置程序请看前一篇..

<2>.创建监听服务程序

 

package com.lixing.ejb;

 

import javax.ejb.ActivationConfigProperty;

import javax.ejb.MessageDriven;

import javax.jms.JMSException;

import javax.jms.Message;

import javax.jms.MessageListener;

import javax.jms.TextMessage;

 

@MessageDriven(

activationConfig={

@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Topic"),

@ActivationConfigProperty(propertyName="destination",propertyValue="topic/mytopic"),

}

)

public class ReceiveBean implements MessageListener{

 

public void onMessage(Message message) {

try {

TextMessage textMessage=(TextMessage)message;

System.out.println(this.getClass()+textMessage.getText());

} catch (JMSException e) {

e.printStackTrace();

}

 

}

}

<3>.创建客户端

 

package com.lixing.ejb;

 

import javax.jms.Destination;

import javax.jms.MessageProducer;

import javax.jms.TextMessage;

import javax.jms.TopicConnection;

import javax.jms.TopicConnectionFactory;

import javax.jms.TopicSession;

import javax.naming.InitialContext;

 

public class TopicSender {

public static void main(String[] args) throws Exception{

//1

InitialContext context=new InitialContext();

 

//2.Get QueueConnectionFactory Object

TopicConnectionFactory factory=(TopicConnectionFactory)context.lookup("ConnectionFactory");

 

//3.Create QueueConnection Object

TopicConnection connection=factory.createTopicConnection();

 

//4.Create QueueSession Object

TopicSession session=connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);

 

//5.Get Destination Object

Destination destination=(Destination)context.lookup("topic/mytopic");

 

//6.Create TextMessage

MessageProducer producer=session.createProducer(destination);

 

//7.Create Sender

TextMessage textMessage=session.createTextMessage("你好,李新");

 

//Sender Message

producer.send(textMessage);

 

session.close();

connection.close();

 

System.out.println("消息已发送");

 

}

}