ActiveMQ Java使用

使用Java实现producer-consumer

生产者程序Producer.java

public class Producer {
    private static final String BROKER_URL=ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final String SUBJECT="waylau-queue";
    public  static final void main(String[] args)throws JMSException{
        //初始化连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(BROKER_URL);
        //获得连接
        Connection conn=connectionFactory.createConnection();
        //启动连接
        conn.start();
        //创建Session,第一个参数表示会话是否在事务中执行,第二个参数设定会话的应答模式
        Session session=conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
        Destination dest=sessin.createQueue(SUBJECT);
        session.createTopic("TOPIC");
        MessageProducer producer=session.createProducer(dest);
        for(int i=0; i<100; i++){
            TextMessage message=session.createTextMessage("Welcome to waylua.com"+1);
            //发送消息
            producer.send(message);
        }
        conn.close();
    }
}

消费者程序 consumer.java

public class Consumer implements MessageListener{
    private static final String BROKER_URL=ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final String SUBJECT="waylau-queue";
    public static void main(String[] args) throws JMSException{
        //初始化ConnectionFactory
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(BROKER_URL);
        //创建MQ连接
        Connection conn=connectionFactory.createConnection();
        conn.start();
        Session session=conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
        Destination dest=session.createQueue(SUBJECT);
        MessageConsumer consumer=session.createConsumer(dest);
        Consumer me=new Consumer();
        consumer.setMessageListener(me);
    }
    @Override
    public void onMessage(Message message){
        TextMessage txtMessage=(TextMessage)message;
    }

}


你可能感兴趣的:(ActiveMQ Java使用)