Activemq 消息发送、接收java代码实现队列模式

package service;


import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;


/** 
 * 生产类
 * @ClassName: ProMq 
 */
public class ProMq {


//队列模式
public static final String queueName = "queue-test";


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


//5. 创建一个目标
Destination destination = MqSession.session().createQueue(queueName);
//6. 创建一个生产者
MessageProducer producer = MqSession.session().createProducer(destination);


for (int i = 0; i < 100; i++) {
//7. 创建消息
TextMessage textMessage = MqSession.session().createTextMessage("test" + i);
//8. 发布消息
producer.send(textMessage);
System.out.println("发送消息" + textMessage.getText());
}
//9. 关闭链接        
MqSession.session().close();
}

}


package service;


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;


import org.apache.activemq.ActiveMQConnectionFactory;


/** 
 * @ClassName: MqSession 
 */
public class MqSession {


public static final String url = "tcp://127.0.0.1:61616";


public static Session session() throws JMSException {


//1. 创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
//2. 创建Connection
Connection connection = connectionFactory.createConnection();
//3. 启动链接        
connection.start();
//4. 创建会话
return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
}

package service;


import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;


/** 
 * 消费类
 * @ClassName: ConMq 
 */
public class ConMq {


//队列模式
public static final String queueName = "queue-test";


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


//5. 创建一个目标
Destination destination = MqSession.session().createQueue(queueName);
//6. 创建一个消费者
MessageConsumer consumer = MqSession.session().createConsumer(destination);
//监听生产者方式接受消息,生产者产生消息才开始接收 需要监听器 实现MessageListener (javax.jms.MessageListener包)
consumer.setMessageListener(new Listener());
}
}


package service;


import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


/** 
 * 创建一个监听器
 * @ClassName: Listener
 */
public class Listener implements MessageListener {


@Override
public void onMessage(Message message) {
try {
System.out.println("消息:" + ((TextMessage) message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(Activemq 消息发送、接收java代码实现队列模式)