- 创建java项目文件
- 导入activemq-all-5.15.2.jar文件,build path
- 新建消息发送类
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
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 JMSProducer {
static String userName=ActiveMQConnection.DEFAULT_USER;
static String password=ActiveMQConnection.DEFAULT_PASSWORD;
static String brokerURL=ActiveMQConnection.DEFAULT_BROKER_URL;
static int sendnum=10;
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(userName, password, brokerURL);
Connection connection = null ;
Session session;// 会话,接受或发送消息的线程
Destination destination;
MessageProducer messageProducer;
try {
connection=connectionFactory.createConnection();
connection.start();
/*
* Session.AUTO_ACKNOWLEDGE 用户成功从receive方法返回的时候,或从MessageListener.onMessage方法
* 成功返回时,会话会自动确认客户收到消息
* Session.CLIENT_ACKNOWLEDGE 客户通过消息的acknowledge方法确认,注意一个被消费的消息将自动确认所
* 有已被会话消费的消息。
* Session.SESSION_TRANSACTED 会话迟钝的确认消息的提交
*/
session=connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
destination=session.createQueue("FirstQueue");
messageProducer=session.createProducer(destination);
sendMessage(session, messageProducer);//发送消息
session.commit();//提交
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection!=null){
try {
connection.close();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/*
* 产生消息并发消息
*/
public static void sendMessage(Session session,MessageProducer messageProducer) throws JMSException {
for(int i=0;i<sendnum;i++){
TextMessage textMessage=session.createTextMessage("Message"+i);
messageProducer.send(textMessage);
System.out.println("开始发送消息Message"+i);
}
// TODO Auto-generated method stub
}
}

