ActiveMQ生产者和消费者案例

一、启动ActiveMQ

ActiveMQ生产者和消费者案例_第1张图片

 ActiveMQ生产者和消费者案例_第2张图片

二、生产者代码 

/**
 * @program: activemqdemo
 * @description:
 * @author: hq.zheng
 * @create: 2019-08-17 14:45
 */
public class Producer {

    public static void main(String[] args) throws JMSException {
        // ConnectionFactory :连接工厂,JMS 用它创建连接
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD, "tcp://127.0.0.1:61616");

        //JMS 客户端到JMS Provider 的连接
        Connection connection = connectionFactory.createConnection();
        //启动连接
        connection.start();

        //Session: 一个发送或接收消息的线程,自动签收
        Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        //Destination :消息的目的地;消息发送给谁.
        //获取session注意参数值my-queue是Query的名字
        Destination destination = session.createQueue("my-queue");
        //MessageProducer:消息生产者
        MessageProducer producer = session.createProducer(destination);
        //设置不持久化
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // 发送一条消息
        TextMessage textMessage = session.createTextMessage("This is my first ActiveMQ");
        producer.send(textMessage);

        //关闭连接
        session.close();
        connection.close();
    }

}

运行后

ActiveMQ生产者和消费者案例_第3张图片 

三、消费者代码 

/**
 * @program: activemqdemo
 * @description:
 * @author: hq.zheng
 * @create: 2019-08-17 15:08
 */
public class Receiver {
    public static void main(String[] args) throws JMSException {
        // ConnectionFactory :连接工厂,JMS 用它创建连接
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD, "tcp://127.0.0.1:61616");
        // JMS 客户端到JMS Provider 的连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        // Session: 一个发送或接收消息的线程
        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        // Destination :消息的目的地;消息发送给谁.
        // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
        Destination destination = session.createQueue("my-queue");
        // 消费者,消息接收者
        MessageConsumer consumer = session.createConsumer(destination);
        while (true) {
            TextMessage message = (TextMessage) consumer.receive();
            if (null != message) {
                System.out.println("收到消息:" + message.getText());
                session.commit();
            } else
                break;
        }
        session.close();
        connection.close();

    }
}

运行后

ActiveMQ生产者和消费者案例_第4张图片 

 

你可能感兴趣的:(MQ)