首先到官网下载
打开bin-选择自己电脑对应的版本的bat,双击运行
此时访问本机http://localhost:8161 需要登陆,用户名和密码都是:admin
此时控制台启动成功。创建项目,普通 java项目,引入activeMQ依赖
下面编写生产者类 public class JMSProducer { private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER; private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD; private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL;//默认的连接 private static final int SENDNUM=10;//发送的消息数量 public static void main(String[]args){ ConnectionFactory connectionFactory;//连接工厂 Connection connection = null;//连接 Session session;//会话,接受或者发送消息的线程 Destination destination;//消息目的地 MessageProducer messageProducer;//消息生产者 //实例化连接工厂 connectionFactory=new ActiveMQConnectionFactory(JMSProducer.USERNAME,JMSProducer.PASSWORD,JMSProducer.BROKEURL); try { connection = connectionFactory.createConnection();//通过连接工厂获取连接 connection.start(); session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE); destination =session.createQueue("FirstQueue1");//创建消息队列 messageProducer = session.createProducer(destination);//创建消息生产者 sendMessage(session,messageProducer); session.commit(); } catch (Exception e) { //todo Auto-generated catch block e.printStackTrace(); }finally { if(connection != null){ try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{ for(int i=0;i<JMSProducer.SENDNUM;i++){ TextMessage message = session.createTextMessage("ActiveMQ发送的消息"+i); System.out.println("发送消息:"+"ActiveMQ发送的消息"+i); messageProducer.send(message); } } }
再编写消费者类
public class JMSConsumer3{ private static final String USERNAME = ActiveMQConnectionFactory.DEFAULT_USER; private static final String PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD; private static final String BORKERURL = ActiveMQConnectionFactory.DEFAULT_BROKER_URL; private static final int SENDNUM = 10; public static void main(String []args){ ConnectionFactory connectionFactory; Connection connection = null; Session session ; Destination destination; MessageConsumer messageConsumer ; //实例化工厂 connectionFactory = new ActiveMQConnectionFactory(JMSConsumer3.USERNAME,JMSConsumer3.PASSWORD,JMSConsumer3.BORKERURL); try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE); destination = session.createQueue("SencondQueue"); messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(new Listener());//注册监听器 } catch (JMSException e) { e.printStackTrace(); } } }
public class Listener implements MessageListener { @Override public void onMessage(Message message) { try { System.out.println("收到的消息:"+((TextMessage)message).getText()); } catch (JMSException e) { e.printStackTrace(); } } 运行生产者产生消息,运行消费者消费消息,控制台查看消息生产-消费情况。