JMS学习环境的搭建
1、 打开eclipse,新建项目”learnJMS”
2、 添加JMS相关包,由于我们使用的消息中间件为ActiveMQ,所以需要从ACTIVEMQ_HOME\lib目录下的相关包:
3、创建三个类,Publisher.java,Subscriber.java,Listener.java代码如下:
package ex01;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
public class Publisher {
private TopicConnection connection;
private TopicPublisher publisher;
private TopicSession session;
public Publisher() throws Exception
{
InitialContext init=new InitialContext();
TopicConnectionFactory topicConnectionFactory=(TopicConnectionFactory)init.lookup("TopicCF");
connection=topicConnectionFactory.createTopicConnection();
session=connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic=(Topic)init.lookup("topic1");
publisher=session.createPublisher(topic);
connection.start();
}
public void writeMessage(String message) throws JMSException
{
TextMessage textMessage=session.createTextMessage();
textMessage.setText(message);
publisher.publish(textMessage);
}
public void close() throws JMSException
{
connection.close();
}
public static void main(String[] args)
{
try {
Publisher publisher = new Publisher();
publisher.writeMessage("nihao!");
// publisher.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package ex01;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
public class Subscriber {
private TopicConnection connection;
private TopicSession session;
private TopicSubscriber subscriber;
public Subscriber() throws Exception
{
InitialContext init=new InitialContext();
TopicConnectionFactory connectionFactory=(TopicConnectionFactory)init.lookup("TopicCF");
connection=connectionFactory.createTopicConnection();
session=connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic=(Topic)init.lookup("topic1");
subscriber=session.createSubscriber(topic);
subscriber.setMessageListener(new Listener());
connection.start();
}
public void close() throws JMSException
{
connection.close();
}
public static void main(String[] args) {
try {
Subscriber sub=new Subscriber();
// sub.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package ex01;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class Listener implements MessageListener {
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
System.out.println("message is :"+textMessage.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、启动ActiveMQ,然后运行Subscriber.java。Publisher.java类
可以看到Subscriber收到了Publisher发送的信息:nihao。
JMS学习环境搭建成功。下一节我们学习JMSAPI。