• Java ActiveMQ 示例


    所需引入Jar包:

      jms-1.1.jar

      activemq-all-5.15.0.jar

    生产者


    package com.mousewheel.demo; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; public class MQProducerDemo { public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.31.33:61616"); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Destination destination = session.createQueue("test-queue"); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); MqBean bean = new MqBean(); bean.setAge(1); for (int i = 0; i < 1000; i++) { bean.setName("Jack " + i); producer.send(session.createObjectMessage(bean)); } producer.close(); System.out.println("Send finished"); } catch (Exception e) { // TODO: handle exception } finally { if (null != connection) { connection.close(); } } } }

    消费者


    package com.mousewheel.demo; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; public class MQConsumerDemo { public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.31.33:61616"); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue("test-queue"); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { MqBean bean = (MqBean) ((ObjectMessage) message).getObject(); System.out.println(bean); if (null != message) { System.out.println("收到消息" + bean.getName()); } } catch (Exception e) { // TODO: handle exception } } }); System.out.println("Begin listen"); } catch (Exception e) { // TODO: handle exception } } }
  • 相关阅读:
    【1】
    正则表达式 re模块
    模块—— 序列化模块、random模块、os模块 、 sys模块、hashlib模块、collections模块
    编码转换 文件的操作
    函数进阶3 —— 生成器、yield from
    函数的进阶2
    函数进阶 —— 动态参数、内置空间、函数嵌套
    初识函数 函数参数 三元运算
    Sringboot jdbc 操作数据库
    python使用subprocess执行linux命令
  • 原文地址:https://www.cnblogs.com/mousewheel/p/7523555.html
Copyright © 2020-2023  润新知