ActiveMQ 实例
转载http://blog.csdn.net/fover717/archive/2009/06/24/4294122.aspx
例子一:
ProducerTool.java用于发送消息:
- import javax.jms.Connection;
- import javax.jms.DeliveryMode;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.MessageProducer;
- import javax.jms.Session;
- import javax.jms.TextMessage;
- import org.apache.activemq.ActiveMQConnection;
- import org.apache.activemq.ActiveMQConnectionFactory;
- public class ProducerTool {
- private String user = ActiveMQConnection.DEFAULT_USER;
- private String password = ActiveMQConnection.DEFAULT_PASSWORD;
- private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
- private String subject = "TOOL.DEFAULT";
- private Destination destination = null;
- private Connection connection = null;
- private Session session = null;
- private MessageProducer producer = null;
- // 初始化
- private void initialize() throws JMSException, Exception {
- ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
- user, password, url);
- connection = connectionFactory.createConnection();
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- destination = session.createQueue(subject);
- producer = session.createProducer(destination);
- producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- }
- // 发送消息
- public void produceMessage(String message) throws JMSException, Exception {
- initialize();
- TextMessage msg = session.createTextMessage(message);
- connection.start();
- System.out.println("Producer:->Sending message: " + message);
- producer.send(msg);
- System.out.println("Producer:->Message sent complete!");
- }
- // 关闭连接
- public void close() throws JMSException {
- System.out.println("Producer:->Closing connection");
- if (producer != null)
- producer.close();
- if (session != null)
- session.close();
- if (connection != null)
- connection.close();
- }
- }
ConsumerTool.java用于接受消息,我用的是基于消息监听的机制,需要实现MessageListener接口,这个接口有个onMessage方法,当接受到消息的时候会自动调用这个函数对消息进行处理。
- import javax.jms.Connection;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.MessageConsumer;
- import javax.jms.Session;
- import javax.jms.MessageListener;
- import javax.jms.Message;
- import javax.jms.TextMessage;
- import org.apache.activemq.ActiveMQConnection;
- import org.apache.activemq.ActiveMQConnectionFactory;
- public class ConsumerTool implements MessageListener {
- private String user = ActiveMQConnection.DEFAULT_USER;
- private String password = ActiveMQConnection.DEFAULT_PASSWORD;
- private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
- private String subject = "TOOL.DEFAULT";
- private Destination destination = null;
- private Connection connection = null;
- private Session session = null;
- private MessageConsumer consumer = null;
- // 初始化
- private void initialize() throws JMSException, Exception {
- //连接工厂是用户创建连接的对象,这里使用的是ActiveMQ的ActiveMQConnectionFactory根据url,username和password创建连接工厂。
- ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
- user, password, url);
- //连接工厂创建一个jms connection
- connection = connectionFactory.createConnection();
- //是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //不支持事务
- //目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象,两种消息传递方式:点对点和发布/订阅
- destination = session.createQueue(subject);
- //会话创建消息的生产者将消息发送到目的地
- consumer = session.createConsumer(destination);
- }
- // 消费消息
- public void consumeMessage() throws JMSException, Exception {
- initialize();
- connection.start();
- System.out.println("Consumer:->Begin listening...");
- // 开始监听
- consumer.setMessageListener(this);
- // Message message = consumer.receive();
- }
- // 关闭连接
- public void close() throws JMSException {
- System.out.println("Consumer:->Closing connection");
- if (consumer != null)
- consumer.close();
- if (session != null)
- session.close();
- if (connection != null)
- connection.close();
- }
- // 消息处理函数
- public void onMessage(Message message) {
- try {
- if (message instanceof TextMessage) {
- TextMessage txtMsg = (TextMessage) message;
- String msg = txtMsg.getText();
- System.out.println("Consumer:->Received: " + msg);
- } else {
- System.out.println("Consumer:->Received: " + message);
- }
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
如果想主动的去接受消息,而不用消息监听的话,把consumer.setMessageListener(this)改为Message message = consumer.receive(),手动去调用MessageConsumer的receive方法即可。
下面是测试类Test.java:
- import javax.jms.JMSException;
- mport org.apache.activemq.ActiveMQConnection;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) throws JMSException, Exception {
- // TODO Auto-generated method stub
- ConsumerTool consumer = new ConsumerTool();
- ProducerTool producer = new ProducerTool();
- System.out.println(ActiveMQConnection.DEFAULT_BROKER_URL+"------------");
- // 开始监听
- consumer.consumeMessage();
- // 延时500毫秒之后发送消息
- Thread.sleep(500);
- producer.produceMessage("Hello, world!");
- producer.close();
- // 延时500毫秒之后停止接受消息
- Thread.sleep(500);
- consumer.close();
- }
- }
例子二:
package mydemo;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
public class KSend {
private Connection connection;
private Session session;
private MessageProducer publisher;
private Topic topic;
private Topic control;
private String url = "failover:(tcp://localhost:61616)?initialReconnectDelay=100&maxReconnectAttempts=5";
public void init() {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
url);
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 对方的topic 用于向 对方发消息
topic = session.createTopic("topic.oagent.crm");
// 本机 topic 用于监听
control = session.createTopic("topic.appserver.crm");
publisher = session.createProducer(topic);
// 设置持久方式
//publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
//session.createConsumer(control).setMessageListener(this);
connection.start();
// this.sendmessage();
} catch (JMSException e) {
e.printStackTrace();
}
}
protected void sendmessage() {
MapMessage msg2;
try {
msg2 = session.createMapMessage();
// 生成MapMessage 消息对象
// 特定字段放入Property数据区内
msg2.setStringProperty("messageType", "CrmMessage");// 设置消息类型
msg2.setStringProperty("topicId", "你的这边的topicId");// 设置Topic
// 如果需要消息回复,会根据这个topiID
// 传回消息
// msg2.setIntProperty("billcodeID","此条记录的唯一ID");
msg2.setStringProperty("loginName", "填表人的登录名");// 登录OA的 那个名字
msg2.setStringProperty("title", "表单的标题");
msg2.setStringProperty("remark", "可以不填 预留");
// msg2.setIntProperty("requestLevel", "紧急程度 正常 0 ;重要 1;紧急 2 ");
msg2.setString("desc002sz", "");
publisher.send(msg2);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close() throws JMSException {
System.out.println("Producer:->Closing connection");
if (publisher != null)
publisher.close();
if (session != null)
session.close();
if (connection != null)
connection.close();
}
public static void main(String[] args) {
KSend kao = new KSend();
kao.init();
kao.sendmessage();
try {
kao.close();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package mydemo;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
public class CReceive implements MessageListener {
private Connection connection;
private Session session;
private MessageProducer publisher;
private Topic topic;
private Topic control;
private String url = "failover:(tcp://localhost:61616)?initialReconnectDelay=100&maxReconnectAttempts=5";
public void init() {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
url);
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 对方的topic 用于向 对方发消息
topic = session.createTopic("topic.oagent.crm");
// 本机 topic 用于监听
control = session.createTopic("topic.appserver.crm");
publisher = session.createProducer(control);
// 设置持久方式
//publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
session.createConsumer(topic).setMessageListener(this);
connection.start();
// this.sendmessage();
} catch (JMSException e) {
e.printStackTrace();
}
}
public void onMessage(Message message) {
try {
if (message instanceof MapMessage) {
MapMessage revMessage = (MapMessage) message;
System.out.println(revMessage.getStringProperty("remark"));
System.out.println("接收消息:"+revMessage.getStringProperty("messageType"));
} else {
System.out.println("其它类型消息!");
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public void close() throws JMSException {
System.out.println("Consumer:->Closing connection");
if (publisher != null)
publisher.close();
if (session != null)
session.close();
if (connection != null)
connection.close();
}
public static void main(String[] args){
CReceive kao=new CReceive();
kao.init();
// try {
// kao.close();
// } catch (JMSException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}