ActiveMQ学习教程

一、activemq安装

官网地址:https://activemq.apache.org/

具体安装过程不赘述,解压即安装,

二、使用

activemq有queuetopic两种模式,

我们以queue模式为例,进行一次java编码

生产者:

public class JmsProduce {
    public static void main(String[] args) {
        // 1 创建连接工场
        ConnectionFactory connect = new ActiveMQConnectionFactory("tcp://192.168.2.128:61616");
        try {
            Connection connection = connect.createConnection();
            connection.start();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue testQueue = session.createQueue("TEST1");
            MessageProducer producer = session.createProducer(testQueue);
            ActiveMQTextMessage textMessage = new ActiveMQTextMessage();
            textMessage.setText("你好!");
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            producer.send(textMessage);
             System.out.println("activemq生产者发送消息");
            session.commit();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

消费者:

public class JmsConsume {
    public static void main(String[] args) {
        ConnectionFactory connect = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://192.168.2.128:61616");
        try {
            Connection connection = connect.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue testqueue = session.createQueue("TEST1");
            MessageConsumer consumer = session.createConsumer(testqueue);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    if (message instanceof TextMessage) {
                        try {
                            String text = ((TextMessage) message).getText();
                            System.out.println(text);
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

其他后续再补

posted @ 2019-07-28 21:55  HeliusKing  阅读(744)  评论(0编辑  收藏  举报