ActiveMQ消息隊列

ActiveMQ下載與部署

官網下載

http://activemq.apache.org/download.html

 

解壓打開出現一下目錄

 

 

啓動ActiveMQ之前,記得安裝JDK並配置JDK環境變量 

https://blog.csdn.net/renlianggee/article/details/90023464

JDK配置好啓動ActiveMQ

啓動成功 

 

打開瀏覽器

http://localhost:8161  默認用戶名:admin,密碼:admin

 

ActiveMQ消費者發送消息代碼

依賴添加

        <!--activeMQ依賴-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
            <version>5.15.11</version>
        </dependency>

Java代碼實現

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSProducer {
    //默認鏈接用戶
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默認鏈接密碼
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默認鏈接地址
    private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
    //默認發送消息數
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;//鏈接工廠
        //鏈接
        Connection connection=null;
        Session session;
        Destination destination;
        MessageProducer messageProducer;
        //實例化工廠
        connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKER_URL);
        try {
            connection = connectionFactory.createConnection();//通過鏈接工廠
            //啓動鏈接
            connection.start();
            //Boolean.TRUE支持事務  Session.AUTO_ACKNOWLEDGE爲自動確認,客戶端發送和接收消息不需要做額外的工作。
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //創建消息隊列
            destination = session.createQueue("FirstQueue1");
            //創建消息生產者
            messageProducer = session.createProducer(destination);
            //發送消息
            sendMessage(session, messageProducer);
            //提交事務
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    /**
     * 發送消息
     * @param session
     * @param messageProducer
     * @throws JMSException
     */
    public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            TextMessage textMessage = session.createTextMessage("發送消息:" + "ActiveMQ 發送的消息" + i);
            System.out.print("發送消息:" + "ActiveMQ 發送的消息" + i);
            messageProducer.send(textMessage);
        }
    }
}

代碼結果查看 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章