天天看點

ActiveMQ入門案例-生産者代碼實作

<–start–>

使用Java程式操作ActiveMQ生産消息,代碼的複雜度較高,但也沒有默寫下來的必要。

開發ActiveMQ首先需要導入activemq-all.jar包,如果是maven項目,就需要在pom檔案中導入坐标。本例中建立的是一個maven項目,是以在pom檔案中引入坐标:

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.14.0</version>
</dependency>      

要測試代碼就需要引入juint坐标:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>      

Java代碼操作ActiveMQ生産消息:

public class ActiveMQProducer {
    @Test
    public void testProduceMQ() throws Exception {
        // 連接配接工廠
        // 使用預設使用者名、密碼、路徑
        // 路徑 tcp://host:61616
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        // 擷取一個連接配接
        Connection connection = connectionFactory.createConnection();
        // 建立會話
        Session session = connection.createSession(true,
                Session.AUTO_ACKNOWLEDGE);
        // 建立隊列或者話題對象
        Queue queue = session.createQueue("HelloWorld");
        // 建立生産者 或者 消費者
        MessageProducer producer = session.createProducer(queue);

        // 發送消息
        for (int i = 0; i < 10; i++) {
            producer.send(session.createTextMessage("你好,activeMQ:" + i));
        }
        // 送出操作
        session.commit();

    }
}