ActiveMQ 的下载和发送消息、接受消息及其事务的基本使用

本文介绍了如何使用Apache ActiveMQ进行消息生产与接收,包括创建连接、会话、队列、生产者和消费者,以及使用回调和监听器实现异步操作。涵盖了发送文本、对象、地图和字节消息的示例,并展示了消费者如何处理不同类型的消息。
摘要由CSDN通过智能技术生成

下载地址

https://activemq.apache.org/

发送消息

public class ActivemqProducerService {

    public void sendMessage() throws Exception {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://127.0.0.1:61616");

        Connection connection = activeMQConnectionFactory.createConnection();

        //true -- 开启事务;Session.AUTO_ACKNOWLEDGE -- 自动确认
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("user");
        MessageProducer messageProducer = session.createProducer(queue);

        //持久化,默认是开启的
        messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

        //设置过期时间
        //messageProducer.setTimeToLive(1000);
        //设置优先级,数值越大优先级越高
        //messageProducer.setPriority(9);


        TextMessage textMessage = session.createTextMessage("hello!!!");
        messageProducer.send(textMessage);


        ObjectMessage objectMessage = session.createObjectMessage();
        objectMessage.setObject(new MyUser("admin","admin"));
        messageProducer.send(objectMessage);

        MapMessage mapMessage = session.createMapMessage();
        mapMessage.setString("key", "value");
        messageProducer.send(mapMessage);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeUTF("World!!!");
        messageProducer.send(bytesMessage);

		//提交事务
        session.commit();

        System.out.println("发送完成");
        connection.close();
    }

    /**
     * 有回调的发送(成功或异常)
     * @throws JMSException
     */
    public void sendMessage2() throws JMSException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://127.0.0.1:61616");
        Connection connection = factory.createConnection();

        //false -- 关闭事务;Session.AUTO_ACKNOWLEDGE -- 自动确认
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Queue queue = session.createQueue("user");
        ActiveMQMessageProducer messageProducer = (ActiveMQMessageProducer) session.createProducer(queue);

        CountDownLatch countDownLatch = new CountDownLatch(1);

        TextMessage textMessage = session.createTextMessage("hello!!!");
        messageProducer.send(textMessage, new AsyncCallback() {
            @Override
            public void onSuccess() {
                countDownLatch.countDown();
                System.out.println("发送成功");
            }

            @Override
            public void onException(JMSException e) {
                System.out.println("发送失败");
            }
        });

    }

    public static void main(String[] args) throws Exception {
        ActivemqProducerService activemqProducerService = new ActivemqProducerService();
        activemqProducerService.sendMessage();
    }

}

接受消息

public class ActivemqConsumerService {

    public void receiveMessage() throws Exception {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://127.0.0.1:61616");

        activeMQConnectionFactory.setTrustAllPackages(true);
        Connection connection = activeMQConnectionFactory.createConnection();

        //false -- 关闭事务;Session.CLIENT_ACKNOWLEDGE -- 手动确认
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue("user");
        MessageConsumer messageConsumer = session.createConsumer(queue);
        connection.start();

        while (true) {
            Message message = messageConsumer.receive();
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println(textMessage.getText());
            }
            if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                Enumeration mapNames = mapMessage.getMapNames();
                while (mapNames.hasMoreElements()) {
                    String s = mapNames.nextElement().toString();
                    System.out.println(s + " --- " + mapMessage.getString(s));
                }
            }
            if (message instanceof ObjectMessage) {
                Object object = (Object) ((ObjectMessage) message).getObject();
            	if (object instanceof List) {
                	List list = (List) object;
                	System.out.println(list);
            	}
            	if (object instanceof MyUser) {
            	    MyUser myUser = (MyUser) object;
           	     	System.out.println(myUser);
            	}
            }
            if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                StringBuilder stringBuilder = new StringBuilder();
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = bytesMessage.readBytes(b)) != -1) {
                    stringBuilder.append(new String(b, 0, len));
                }
                System.out.println(stringBuilder.toString());
            }

            //确认消息
            message.acknowledge();
        }

    }

    public static void main(String[] args) throws Exception {
        ActivemqConsumerService activemqConsumerService = new ActivemqConsumerService();
        activemqConsumerService.receiveMessage();
    }
}

使用监听器请看
https://wwp666.blog.csdn.net/article/details/119820270

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值