ActiveMq環境搭建,及簡單運用。

1、先下載安裝運行(以linux爲例)

下載地址:http://activemq.apache.org/components/classic/download/

如下圖:
在這裏插入圖片描述
2、上傳虛擬機並解壓

rz -y 命令上傳到虛擬機/opt目錄下
tar -zxvf apache-activemq-5.15.11-bin.tar.gz 解壓到當前目錄

3、解壓完進入到bin目錄下
如下圖
在這裏插入圖片描述
4、啓動activemq

在bin目錄下執行: ./activemq start  啓動activemq

3種檢查服務是否啓動成功:1、netstat -anp|grep 61616
			         2、ps -ef|grep activemq|grep -v grep
			         3、lsof -i:61616

5、瀏覽器訪問activemq

瀏覽器直接訪問http://localhost:8161/admin
彈出輸入用戶密碼窗口,用戶名密碼默認是admin
可以改登錄的用戶名和密碼,在conf文件夾activemq.xml裏配置

如下圖:
在這裏插入圖片描述
6、簡單代碼運用
activemq集成到springBoot中,配置maven如下代碼

  <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-activemq</artifactId>
  </dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-web</artifactId>
		<version>5.15.11</version>
	</dependency>

7、消息生產者代碼如下

public static void testJmsproduct() throws JMSException {

        //1、創建activeMq連接工廠
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2、創建activemq連接
        Connection connection = activeMQConnectionFactory.createConnection();
        //啓動連接
        connection.start();
        //3、創建session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4、創建隊列
        Queue queue = session.createQueue(QUEUE);
        //5、創建一個消息生產者
        MessageProducer producer = session.createProducer(queue);

        //6、開始往隊列中添加消息
        for (int i = 1; i <= 3; i++) {
            String text = "第【" + i + "】次消息,發佈成功!!!!";
            TextMessage textMessage = session.createTextMessage(text);
            producer.send(textMessage);
        }
        session.close();
        connection.close();
        System.out.println("消息發佈成功了寶貝兒。。。。。");
    }

運行結果如下圖:
在這裏插入圖片描述
8、消息消費者代碼如下

 public static void jmsTestConsumer() throws JMSException {
        //1、創建連接工廠
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2、創建連接
        Connection connection = activeMQConnectionFactory.createConnection();
        //3、啓動連接
        connection.start();
        //4、創建session會話
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5、創建隊列名稱
        Queue queue = session.createQueue(QUEUE);
        //6、創建一個消費者
        MessageConsumer consumer = session.createConsumer(queue);
        while(true){
            //獲取消息,默認返回Message ,生產者是TextMessage 所以這裏需要強轉成TextMessage
            TextMessage receive = (TextMessage) consumer.receive();
            if (receive!=null) {
                System.out.println("消費者消費消息:"+receive.getText());
            } else {
                break;
            }
        }
        session.close();
        connection.close();
    }

運行結果如下圖:
在這裏插入圖片描述

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